Reputation: 857
I wonder how can I break a byte in 4 pairs of two bits.
E.g. I am given the following:
0xf0; /* 11110000 */
and the output should be:
11
11
00
00
Upvotes: 1
Views: 1001
Reputation: 1929
you should check out the bitwise operations. They provide everything you need.
bitwise & for masking
0xf0 & 0b11000000 = 0b11000000
bit shift >>
0b11000000 >> 6 = 0b00000011
edit:
0b00000011 = (0xf0 & 0b11000000) >> 6;
0b00000011 = (0xf0 & 0b00110000) >> 4;
0b00000000 = (0xf0 & 0b00001100) >> 2;
0b00000000 = 0xf0 & 0b00000011;
Upvotes: 4
Reputation: 64308
void printBits(int byte)
{
printf("%d%d\n",byte>>7,(byte>>6)&1);
printf("%d%d\n",(byte>>5)&1,(byte>>4)&1);
printf("%d%d\n",(byte>>3)&1,(byte>>2)&1);
printf("%d%d\n",(byte>>1)&1,byte&1);
}
Upvotes: 1