shinzou
shinzou

Reputation: 6192

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

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).

Upvotes: 1

Views: 82

Answers (1)

Amit
Amit

Reputation: 46323

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;

Upvotes: 2

Related Questions