extract 4 bits from 8 bits ....

Hi all,

first, excuse my english :wink:

Well,

i have a variable with 7 bits like 1000110. i want to extract the First 4 bits like 1000 from my variable and put it in another variable
and extract also the last 3 bits like 110.
i don't know how to do this
can somebody help me for this problem.

thanks by advance for your help

Best regards

Patrick

Using bit masks and shift

byte x = B01101110;
byte y = x & B00001111; // y will be set to B00001110
byte z = x >> 4; // z will be set to B00000110
a = 1000110
var1 = (a & 0x78) >> 3;
var2 = (a & 0x7);

generally you need to mask with all the bits on (0x78 = 0111 1000) that youwant to keep and then shift to the right by the number of bits you want to eliminate (in this case 3). It is more common to split into 4 bits so mask is 0xf for one var and 0xf0 and then shift by 4 for the other (or just shift by 4).

In the case of a byte variable (which is an 8-bit unsigned type) shifting right by four is
enough, a masking operation is not needed because there are only 8 bits and unsigned
shift right feeds in zeros (no so for a signed shift).

thank you for your help

it's ok :wink:
you're the best :wink:

and after, i do this :

byte x = code_led; // like B1000100
byte y = code_led & B0000111; // y = code_ligne => B100
byte z = code_led >> 3; // z code_col => B1000

y = y | B110; // new value
z = z | B0100;

i want to join y & z to form a new code_led

how can i do this ?

thanks

PAtrick

The reverse.

You shift to the right by how many bits you need (creating zeros in the bottom part) and then 'or' in the other part

(x << 3) | y

thank you very much for your help.

i continue now my project

Bye