我有一个字节数组(字节[16])与一个字节中的每个小区:基地2字节数组串
0000000000010010 -> [0][0] ..... [1][0][0][1][0].
如何获得与基体2的逻辑结果?
我想得到结果:18
。我使用C#。
我有一个字节数组(字节[16])与一个字节中的每个小区:基地2字节数组串
0000000000010010 -> [0][0] ..... [1][0][0][1][0].
如何获得与基体2的逻辑结果?
我想得到结果:18
。我使用C#。
应该可以使用以下,对你的字节数组是纯粹0
S和1
S)的假设下,(不过,如果是这样的话,一个bool[]
可能会是一个更好的选择),而最显着位是第0个元素。
private int BytesToInt(byte[] byteArray)
{
// Start with zero
int result = 0;
foreach (var b in byteArray)
{
// For each item in the array, first left-shift the result one bit
result <<= 1;
// If the byte is non-zero, set the lowest bit in the result
if (b != 0) result |= 1;
}
return result;
}
你能解释一下结果<< = 1; 和结果| = 1;意思? 我从来没有见过这些。 –
'<< ='是左移赋值运算符(在此相当于:'result = result << 1','| ='是或赋值运算符(相当于'result = result | 1') – Iridium
我的数学缺乏理解左移的技巧,但是要感谢解释 –
你应该有点小玩意儿。甲LINQ单行:
public static ushort ToUShort(this byte[] buffer)
{
const int ushort_bits = sizeof(ushort) * 8 ;
int bits = ushort_bits - 1 ;
return (ushort) buffer
.Take(ushort_bits)
.Select(b => b != 0 ? 1 : 0)
.Aggregate(0 , (acc,b) => acc | (b<<(bits--)))
;
}
或同样简洁(也可能更快):
public static ushort ToUShort(this byte[] buffer)
{
uint acc = 0 ;
int bits = sizeof(ushort) * 8 - 1 ;
int max = sizeof(ushort) * 8 ;
for (int i = 0 ; i < max ; ++i)
{
acc |= (buffer[i]==0?0u:1u)<<(bits--) ;
}
return (ushort) acc ;
}
谢谢,它比以前更快!:) – Michael
喜欢[此](http://stackoverflow.com/questions/11654562/how-convert-字节阵列到字符串)? – Brian
您的数组是否代表一个16位的二进制数,每个字节代表一个位(0或1)? – Alex
也许这样? 'if(BitConverter.IsLittleEndian) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes,0);' –