用C#设置字节数组中的位



我需要用一个短整数值对字节数组进行编码编码规则为表示整数的位是位0-13如果数字为负数,则设置位14比特15总是1。我知道我可以使用BitConverter 将整数放入字节数组

byte[] roll = BitConverter.GetBytes(x);

但是我找不到如何满足我的要求有人知道怎么做吗?

您应该使用位运算符。

解决方案是这样的:

Int16 x = 7;
if(x < 0)
{
Int16 mask14 = 16384; // 0b0100000000000000;
x = (Int16)(x | mask14);
}
Int16 mask15 = -32768; // 0b1000000000000000;
x = (Int16)(x | mask15);
byte[] roll = BitConverter.GetBytes(x);

负数不能依赖GetBytes,因为它是对位的补充,而这不是您所需要的。

相反,您需要进行边界检查以确保数字是可表示的,然后对给定数字的绝对值使用GetBytes。

该方法的参数是"short",因此我们GetBytes返回一个大小为2的字节数组(不需要超过16位(。

其余内容在下面的评论中:

static readonly int MAX_UNSIGNED_14_BIT = 16383;// 2^14-1
public static byte[] EncodeSigned14Bit(short x)
{
var absoluteX = Math.Abs(x);
if (absoluteX > MAX_UNSIGNED_14_BIT) throw new ArgumentException($"{nameof(x)} is too large and cannot be represented");
byte[] roll = BitConverter.GetBytes(absoluteX);
if (x < 0)
{
roll[1] |= 0b01000000; //x is negative, set 14th bit 
}
roll[1] |= 0b10000000; // 15th bit is always set
return roll;
}
static void Main(string[] args)
{
// testing some values
var r1 = EncodeSigned14Bit(16383); // r1[0] = 255, r1[1] = 191
var r2 = EncodeSigned14Bit(-16383); // r2[0] = 255, r2[1] = 255
}

最新更新