How to convert integer to binary string in C#?

Solution 1:

Simple soution:

IntToBinValue = Convert.ToString(6, 2);

Solution 2:

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);

Solution 3:

At least part of the answer is to use decimal.GetBits(someValue) to convert the decimal to its binary representation.

BitConverter.GetBytes can be used, in turn, on the elements returned from decimal.GetBits() to convert integers into bytes.

You may find the decimal.GetBits() documentation useful.

I'm not sure how to go from bytes to decimal, though.

Update: Based on Author's update:

BitConverter contains methods for converting numbers to bytes, which is convenient for getting the binary representation. The GetBytes() and ToInt32() methods are convenient for conversions in each direction. The ToString() overloads are convenient for creating a hexadecimal string representation if you would find that easier to interpret as 1's and 0's.