在C#中,我如何设置2个字节,前10位代表一个十进制值,接下来的6代表不同的十进制值?
因此,如果第一个值为'8'(前10位),第二个'2'(剩余6位),我需要在字节数组中最后得到'0000001000 000010'。
谢谢! 广告
答案 0 :(得分:4)
UInt16 val1 = 8;
UInt16 val2 = 2;
UInt16 combined = (UInt16)((val1 << 6) | val2);
如果在字节数组中需要它,可以将结果传递给BitConverter.GetBytes
method。
byte[] array = BitConverter.GetBytes(combined);
答案 1 :(得分:1)
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');
答案 2 :(得分: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;
}
答案 3 :(得分:0)
ushort value = (8 << 6) | 2;
byte[] bytes = BitConverter.GetBytes(value);