How to convert integer to binary string in C#?

前端 未结 8 1975
失恋的感觉
失恋的感觉 2020-12-02 01:48

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 b

相关标签:
8条回答
  • 2020-12-02 02:38

    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');
    }
    
    0 讨论(0)
  • 2020-12-02 02:40

    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);
    
    0 讨论(0)
提交回复
热议问题