Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer to binary string in C#?

Tags:

c#

I'm writing a number converter. How can I convert a integer to a binary string in C# WITHOUT using built-in functions (Convert.ToString does different things based on the value given)?

  • Binary -> Sign magnitude
  • Binary -> One's complement
  • Binary > Two's complement
like image 760
Jake Petroules Avatar asked Sep 13 '10 16:09

Jake Petroules


2 Answers

Simple soution:

IntToBinValue = Convert.ToString(6, 2);
like image 105
Miroslav Siska Avatar answered Oct 12 '22 20:10

Miroslav Siska


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);
like image 44
casablanca Avatar answered Oct 12 '22 20:10

casablanca