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)
.
Shift operator only only works on integral types. Using
<<
causes implicit integral promotion, type castingb
to anint
and "protecting" the higher bits.To solve, use
temp = ((unsigned char)(b << 4)) >> 4;