Convert integer to binary in C#
Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.
int value = 8;
string binary = Convert.ToString(value, 2);
Which returns 1000.
easy and fast way to convert an int to binary?
var result = Convert.ToString(number, 2);
– Almost the only use for the (otherwise useless) Convert
class.
How to convert an integer to binary stored in array
You can add some Linq to represent the string
as an array:
string source = Convert.ToString(number, toBase).PadLeft(length, '0');
...
int[] binary = source.Select(c => c - '0').ToArray();
...
bool[] binary = source.Select(c => c == '1').ToArray();
Or you can compute arrays directly:
int[] binary = Enumerable
.Range(1, length)
.Select(i => number / (1 << (length - i)) % 2)
.ToArray();
bool[] binary = Enumerable
.Range(1, length)
.Select(i => number / (1 << (length - i)) % 2 == 1)
.ToArray();
Convert an integer to a binary string with leading zeros
11
is binary representation of 3
. The binary representation of this value is 2
bits.
3 = 20 * 1 + 21 * 1
You can use String.PadLeft(Int, Char)
method to add these zeros.
// convert number 3 to binary string.
// And pad '0' to the left until string will be not less then 4 characters
Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011
How to convert integer to binary string in C#?
Almost all computers today use two's complement representation internally, so if you do a straightforward conversion like this, you'll get the two's complement string:
public string Convert(int x) {
char[] bits = new char[32];
int i = 0;
while (x != 0) {
bits[i++] = (x & 1) == 1 ? '1' : '0';
x >>= 1;
}
Array.Reverse(bits, 0, i);
return new string(bits);
}
That's your basis for the remaining two conversions. For sign-magnitude, simply extract the sign beforehand and convert the absolute value:
byte sign;
if (x < 0) {
sign = '1';
x = -x;
} else {
sign = '0';
}
string magnitude = Convert(x);
For one's complement, subtract one if the number is negative:
if (x < 0)
x--;
string onec = Convert(x);
Is converting Integer to five digit Binary in c# possible?
Use PadLeft
:
var binary = Convert.ToString(number, 2).PadLeft(5, '0');
See a live demo on rextester.
Decimal to Binary Conversion in C#
Try this...
private void button1_Click(object sender, EventArgs e)
{
double dbVlaue = Convert.ToDouble(textBox1.Text);
int quot;
int num;
num = Convert.ToInt32(dbVlaue);
string rem = string.Empty;
while (num > 1)
{
quot = num / 2;
rem += (num % 2).ToString();
num = quot;
}
string bin = " ";
for (int i = rem.Length - 1; i >= 0; i--)
{
bin = bin + rem[i];
}
textBox1.Text = bin.ToString();
}
Converting Decimal to Binary C# using functions
binaryArray[i] = "0"
must be binaryArray[i] = '0'
"0"
is a string
literal while '0'
is a char
and you have an array of char
.
Same for binaryArray[i] = "1"
While the above will solve your problem, I recommend using Convert.ToString(dec, 2)
(as suggested by the dupe marked by mjwills). Of course, this makes only sense if you are interested in the outcome rather than in coding it yourself.
Mind that I deliberately did not address any other issues with the code snippet.
Related Topics
Generics in C#, Using Type of a Variable as Parameter
System.Missingmethodexception: Method Not Found
How to Get the Full Path of Running Process
How to Get Windows Display Settings
Using Regex to Balance Match Parenthesis
Load an Exe File and Run It from Memory
How to Use Reflection to Inspect the Code in a Method
Easiest Way to Parse JSON Response
Create Folder and File on Current User Profile, from Admin Profile
How to Change the Table Names When Using ASP.NET Identity
How to Access Session Variables from Any Class in ASP.NET
Differences in String Compare Methods in C#
Calling Async Method Synchronously
Select N Random Elements from a List<T> in C#
How Do Yield and Await Implement Flow of Control in .Net
How to Check for Nulls in an '==' Operator Overload Without Infinite Recursion