[英]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_first4bits
和u2_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.