2016-10-03 30 views
0

我有一个代码将一个整数转换为它的二进制表示,但我想知道是否有更简单或更容易的方法。我知道在C#中有一个内置方法可以自动为您执行此操作,但这不是我想要使用的方法。C#更简单的将整数转换为无Convert.ToString方法的二进制形式的字符串。

该版本在写入1和0时将循环遍历32位位置,并使用TrimStart删除前导零。

例如,将整数10转换为 二进制中的字符串表示形式为“1010”。

static string IntToBinary(int n) 
{ 
    char[] b = new char[32]; 
    int pos = 31; 
    int i = 0; 

    while (i < 32) // Loops over each of the 32-bit positions while writing ones and zeros. 
    { 
     if ((n & (1 << i)) != 0) 
     { 
      b[pos] = '1'; 
     } 
     else 
     { 
      b[pos] = '0'; 
     } 
     pos--; 
     i++; 
    } 
    return new string(b).TrimStart('0'); // TrimStart removes leading zeroes. 
} 

static void Main() 
{ 
    Console.WriteLine(IntToBinary(300)); 
} 
+0

**为什么**不想使用'Con vert.ToString'? –

回答

0

我想你可以使用一个半字节查找表:

static string[] nibbles = { 
    "0000", "0001", "0010", "0011", 
    "0100", "0101", "0110", "0111", 
    "1000", "1001", "1010", "1011", 
    "1100", "1101", "1110", "1111" 
}; 

public static string IntToBinary(int n) 
{ 
    return 
     nibbles[(n >> 28) & 0xF] + 
     nibbles[(n >> 24) & 0xF] + 
     nibbles[(n >> 20) & 0xF] + 
     nibbles[(n >> 16) & 0xF] + 
     nibbles[(n >> 12) & 0xF] + 
     nibbles[(n >> 8) & 0xF] + 
     nibbles[(n >> 4) & 0xF] + 
     nibbles[(n >> 0) & 0xF] 
    .TrimStart('0'); 
} 
+0

当你理解逻辑时,这看起来更复杂但简单。 – Jared

0

下面是一个简单的LINQ实现:

static string IntToBinary(int n) 
{ 
    return string.Concat(Enumerable.Range(0, 32) 
     .Select(i => (n & (1 << (31 - i))) != 0 ? '1' : '0') 
     .SkipWhile(ch => ch == '0')); 
} 

另外一个使用for循环:

static string IntToBinary(int n) 
{ 
    var chars = new char[32]; 
    int start = chars.Length; 
    for (uint bits = (uint)n; bits != 0; bits >>= 1) 
     chars[--start] = (char)('0' + (bits & 1)); 
    return new string(chars, start, chars.Length - start); 
} 
相关问题