在C#10位,我将如何去设置2个字节,其中第一个10位代表一个十进制值和下一个6代表不同的十进制值?修改的2个字节
因此,如果第一个值是“8”(前10个比特)和第二“2”(剩余6个比特),我需要“0000001000 000010”结束了一个字节数组内。
谢谢! 广告
在C#10位,我将如何去设置2个字节,其中第一个10位代表一个十进制值和下一个6代表不同的十进制值?修改的2个字节
因此,如果第一个值是“8”(前10个比特)和第二“2”(剩余6个比特),我需要“0000001000 000010”结束了一个字节数组内。
谢谢! 广告
UInt16 val1 = 8;
UInt16 val2 = 2;
UInt16 combined = (UInt16)((val1 << 6) | val2);
如果你需要在一个字节数组,你可以传递结果到BitConverter.GetBytes
method。
byte[] array = BitConverter.GetBytes(combined);
int val1 = 8;
int val2 = 2;
// First byte contains all but the 2 least significant bits from the first value.
byte byte1 = (byte)(val1 >> 2);
// Second byte contains the 2 least significant bits from the first value,
// shifted 6 bits left to become the 2 most significant bits of the byte,
// followed by the (at most 6) bits of the second value.
byte byte2 = (byte)((val1 & 4) << 6 | val2);
byte[] bytes = new byte[] { byte1, byte2 };
// Just for verification.
string s =
Convert.ToString(byte1, 2).PadLeft(8, '0') + " " +
Convert.ToString(byte2, 2).PadLeft(8, '0');
不占任何溢出:
private static byte[] amend(int a, int b)
{
// Combine the datum into a 16 bits integer
var c = (ushort) ((a << 6) | (b));
// Fragment the Int to bytes
var ret = new byte[2];
ret[0] = (byte) (c >> 8);
ret[1] = (byte) (c);
return ret;
}
ushort value = (8 << 6) | 2;
byte[] bytes = BitConverter.GetBytes(value);
那是10位还是10位? ;) – demoncodemonkey 2012-02-24 19:48:49
@demoncodemonkey:你的意思是'字节或bits'? :) – sll 2012-02-24 19:50:54
闻起来像功课给我。 – 2012-02-24 19:53:18