4

2 ビットのデータを 1 バイトに挿入する必要があります。

最初の 3 ビット (0,1,2) には 1 から 5 までの数値が含まれます。

最後の 5 ビット (3,4,5,6,7) には 0 から 25 までの数値が含まれます。 [編集: 250 から変更]

私は試した:

byte mybite = (byte)(val1 & val2)

しかし、正直なところ、ビット操作で何をしているのかよくわかりませんが、以前の投稿からこの情報を読むのに多少の助けがありました。

これは、バイトから情報を読み取る方法です。

 // Advanced the position of the byte by 3 bits and read the next 5 bits
 ushort Value1 = Convert.ToUInt16((xxx >> 3) & 0x1F);

 // Read the first 3 bits
 ushort Value2 = Convert.ToUInt16((xxx & 0x7));

前もって感謝します。

4

4 に答える 4

6
int num1 = 4;
int num2 = 156;
int num = (num2 << 3) | num1;

num2次に、3を右にシフトすることで読み取ることができます

int num2Read = num >> 3

そして、あなたは次num1のように読みます(&がnumの最初の3ビットであるマスクのようなものを作成しています)

int num1Read = num & 7

このようにして、最初の数値を 3 ビットにすることができ、2 番目の数値を任意の長さにすることができます。

于 2013-07-08T11:24:11.190 に答える
1

(私があなたの質問を理解したら、特定の場所にビットを追加したい)バイトはxxxx-xxxx

したがって、右端のビットに「追加」したい場合:xxxx-xxxY

byte b=...

b=b | 1

右から 2 番目のビットに追加する場合:xxxx-xxYx

b=b | 2

右から 3 番目のビットに追加する場合:xxxx-xYxx

b=b | 4

右から 4 番目のビットに追加する場合:xxxx-Yxxx

b=b | 8

右から 5 番目のビットに追加する場合:xxxY-xxxx

b=b | 16

別の例:

14 を追加する場合:

ただする

b=b | 14 ビットをアップ xxxx-YYYxビットします

于 2013-07-08T11:20:13.147 に答える
0

If I understand you question correctly, you are looking for a reverse operation to the one you had in you question.

Here is how you can do that (ugly code with casts etc, but shows what's happening with the bits):

byte source = 0xA3; // source = 10100011 = 163
// get bits from source
byte lowbits = (byte)((int)source & 7); // lowbits = 00000011 = 3
byte highbits = (byte)((int)source >> 3); // highbits = 00010100 = 20

Note though that at this point, lowbits contains a value that is between 0 and 7 (not 0 and 5), while highbits contains a value that is between 0 and 31 (not 0 and 250).

// use bits to create copy of original source
byte destination = (byte)(((int)highbits << 3) | (int)lowbits); // destination = 10100011

Also note that if highbits contains a value greater than 31, then some bits will be dropped by this operation. And if lowbits contain a value greater than 7, it may cause some bits from highbits to be overwritten.

于 2013-07-08T11:52:20.643 に答える
0

or操作の代わりに使用andします。IE

byte mybite = (byte)(val1 | val2);

val1 が 0000-0010 (2) で val2 が 1000-0000 (128) の場合、and( &) は 0000-0000 になり、or( |) は 1000-0010 (130) になります。

于 2013-07-08T11:22:32.830 に答える