I need to insert 2 bits of data into a single byte.
First 3 bits (0,1,2) to contain a number between 1 and 5.
Last 5 bits (3,4,5,6,7) to contain a number between 0 and 25. [Edit: Changed from 250]
I tried:
byte mybite = (byte)(val1 & val2)
but to be honest I don't really know what I'm doing with bit operations although I had some help in reading this info from an earlier post which was great.
This is how I read the info 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.
int num1 = 4;
int num2 = 156;
int num = (num2 << 3) | num1;
Then you can read num2
by shifting 3 to the right
int num2Read = num >> 3
And you read num1
like (you are creating something like a mask that &'s the first 3 bits of num)
int num1Read = num & 7
This way, the first number can be 3 bits and the second number can be arbitrarily long
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With