Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert 2 numbers into a byte

Tags:

c#

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.

like image 623
Anonymous Avatar asked Mar 23 '23 06:03

Anonymous


1 Answers

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

like image 103
altschuler Avatar answered Apr 06 '23 04:04

altschuler