Insert 2 numbers in bytes

I need to insert 2 bits of data into one byte.

The first 3 bits (0,1,2) contain a number from 1 to 5.

The last 5 bits (3,4,5,6,7) contain a number from 0 to 25. [Edit: Changed from 250]

I tried:

byte mybite = (byte)(val1 & val2) 

but to be honest, I really donโ€™t know what I am doing with bit operations, although I had some help in reading this information from an earlier post, which was great.

This is how I read information from a byte:

  // 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)); 

Thanks in advance.

+4
source share
4 answers
 int num1 = 4; int num2 = 156; int num = (num2 << 3) | num1; 

Then you can read num2 by moving 3 to the right

 int num2Read = num >> 3 

And you read num1 as (you create something like a mask, which and the first 3 bits of num)

 int num1Read = num & 7 

So the first number can be 3 bits, and the second number can be arbitrarily long

+6
source

(If I understand your question, you want to add a bit to a specific place) Byte xxxx-xxxx

therefore, if you want to โ€œaddโ€ to the rightmost bit: xxxx-xxxY

byte b=...

b=b | 1

If you want to add the second rightmost bit: xxxx-xxYx

b=b | 2

If you want to add the third rightmost bit: xxxx-xYxx

b=b | 4

If you want to add the fourth rightmost bit: xxxx-Yxxx

b=b | 8

If you want to add the fifth rightmost bit: xxxY-xxxx

b=b | 16

Differnet example:

if you want to add 14:

just

b=b | 14 b=b | 14 which will increment the xxxx-YYYx

+1
source

Use or instead of and . IE

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

If val1 is 0000-0010 (2), and val2 is 1000-0000 (128), and ( & ) will lead to 0000-0000, and or ( | ) will lead to 1000 -0010 (130).

0
source

If I understand your question correctly, you are looking for the reverse operation with what you had in the question.

Here's how you can do it (ugly code with ghosts, etc., but shows what happens to 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 that at this moment lowbits contains a value that is between 0 and 7 (not 0 and 5), and 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 deleted by this operation. And if lowbits contains a value greater than 7, this can lead to overwriting some bits from highbits .

0
source

Source: https://habr.com/ru/post/1490255/


All Articles