繁体   English   中英

c#使用低位和高位将两个ushort值转换为一个字节

[英]c# convert two ushort values into one byte using low bits and high bits

我有一个问题,我需要转换为两个u短数字,说1和2到1个字节。 有点像

0 0 1 0值2和0 0 0 1值1

所以结果我得到了一个值00100001的字节,可能00100001 ,我不是一个主机低级编码器。

这应该工作:

 (byte)(((value1 & 0xF)<<4) | (value2 & 0xF))

我不是高级底层编码器。

好,现在是时候成为一体了!

编辑:在问题足够清楚以至于不能完全理解所需内容之前就做出了这个答案。 查看其他答案。

在两个数字上使用“位掩码”,然后将它们按位“或”在一起。
我还不太清楚您到底想要什么,但是假设您想要第一个ushort的前4位,然后是第二个ushort的后4位。 注意: ushort为16位宽。

ushort u1 = 44828; //10101111 00011100 in binary
ushort u2 = 65384; //11111111 01101000 in binary

int u1_first4bits = (u1 & 0xF000) >> 8;

“掩码”为0xF000。 它掩盖了u1:

44828         1010 1111 0001 1100
0xF000        1111 0000 0000 0000
bitwise-AND   1010 0000 0000 0000

问题是,这个新数字仍然是16位长-我们必须将其>> 8移位8位
0000 0000 1010 0000

然后对第二个数字进行另一个掩码操作:

int u2_last4bits  =  u2 & 0x000F;

图说:

65384         1111 1111 0110 1000
0x000F        0000 0000 0000 1111
bitwise-AND   0000 0000 0000 1000

在这里,我们不需要移动位,因为它们已经在我们想要的位置。
然后我们对它们进行按位或运算:

byte b1 = (byte)(u1_first4bits | u2_last4bits);
//b1 is now 10101000 which is 168

图说:

u1_first4bits 0000 0000 1010 0000
u2_last4bits  0000 0000 0000 1000
bitwise-OR    0000 0000 1010 1000

请注意, u1_first4bitsu2_first4bits必须为int类型-这是因为C#按位操作返回int 要创建byte b1 ,我们必须将bitwase-OR操作强制转换为一个字节。

假设您要使用2个ushort(每个16位)并将其转换为32位表示形式(整数),则可以使用“ BitArray”类,将其填充为4字节数组,然后将其转换为整数。

以下示例将产生:

 00000000 00000010 00000000 00000001

这是

 131073

作为整数。

ushort x1 = 1;
ushort x2 = 2;

//get the bytes of the ushorts. 2 byte per number. 
byte[] b1 = System.BitConverter.GetBytes(x1);
byte[] b2 = System.BitConverter.GetBytes(x2);

//Combine the two arrays to one array of length 4. 
byte[] result = new Byte[4];
result[0] = b1[0];
result[1] = b1[1];
result[2] = b2[0];
result[3] = b2[1];

//fill the bitArray.
BitArray br = new BitArray(result);

//test output.
int c = 0;
for (int i = br.Length -1; i >= 0; i--){

    Console.Write(br.Get(i)? "1":"0");
    if (++c == 8)
    {
        Console.Write(" ");
        c = 0;
    }
}

//convert to int and output. 
int[] array = new int[1];
br.CopyTo(array, 0);
Console.WriteLine();
Console.Write(array[0]);

Console.ReadLine();

当然,您可以更改此示例,并为每个ushort 丢弃 1个字节。 但这不是正确的“转换”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM