Getting four bits from the right only in a byte using bit shift operations

95 views Asked by At

I wanted to try to get only the four bits from the right in a byte by using only bit shift operations but it sometimes worked and sometimes not, but I don't understand why.

Here's an example:

unsigned char b = foo; //say foo is 1000 1010
unsigned char temp=0u;

temp |= ((b << 4) >> 4);//I want this to be 00001010

PS: I know I can use a mask=F and do temp =(mask&=b).

1

There are 1 answers

4
Amit On BEST ANSWER

Shift operator only only works on integral types. Using << causes implicit integral promotion, type casting b to an int and "protecting" the higher bits.

To solve, use temp = ((unsigned char)(b << 4)) >> 4;