简体   繁体   中英

How to convert integer to binary string in 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

简单的方法:

IntToBinValue = Convert.ToString(6, 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);

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.

   var a = Convert.ToString(4, 2).PadLeft(8, '0');

Here's mine: (The upper part convert 32-char binary string to 32-bit integer, the lower part convert 32-bit integer back to 32-char binary string). Hope this helps.

        string binaryString = "011100100111001001110011";
        int G = 0;

        for (int i = 0; i < binaryString.Length; i++)
            G += (int)((binaryString[binaryString.Length - (i + 1)] & 1) << (i % 32));

        Console.WriteLine(G); //‭7500403‬
        binaryString = string.Empty;

        for (int i = 31; i >= 0; i--)
        {
            binaryString += (char)(((G & (1 << (i % 32))) >> (i % 32)) | 48);
        }

        Console.WriteLine(binaryString); //00000000011100100111001001110011

Here is an elegant solution:

// Convert Integer to binary and return as string
private static string GetBinaryString(Int32 n)
{
    char[] b = new char[sizeof(Int32) * 8];

    for (int i = 0; i < b.Length; i++)
        b[b.Length-1 - i] = ((n & (1 << i)) != 0) ? '1' : '0';

    return new string(b).TrimStart('0');
}

This is an unsafe implementation:

    private static unsafe byte[] GetDecimalBytes(decimal d)
    {
        byte* dp = (byte*) &d;
        byte[] result = new byte[sizeof(decimal)];
        for (int i = 0; i < sizeof(decimal); i++, dp++)
        {
            result[i] = *dp;
        }
        return result;
    }

And here is reverting back:

    private static unsafe decimal GetDecimal(Byte[] bytes)
    {
        if (bytes == null)
            throw new ArgumentNullException("bytes");

        if (bytes.Length != sizeof(decimal))
            throw new ArgumentOutOfRangeException("bytes", "length must be 16");

        decimal d = 0;
        byte* dp = (byte*)&d;
        byte[] result = new byte[sizeof(decimal)];
        for (int i = 0; i < sizeof(decimal); i++, dp++)
        {
            *dp = bytes[i];
        }
        return d;
    }

You can construct the representations digit by digit from first principles.

Not sure what built-in functions you don't want to use, but presumably you can construct a string character by character?

  1. Start with the highest power of two greater than the number.
  2. Push a "1" into your string.
  3. Subtract that power of two from your number.
  4. Take the next-lowest power of two. If you've reached one-half, stop. You're done.
  5. If the number that's left is greater than this power of two, go back to step 2. If not, push a "0" into the string and go back to step 4.

For one's complement and two's complement, calculate those with an additional step .

Or is this way too basic for what you need?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM