Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I create a bitmaped data in c?

I am trying to create a bitmaped data in , here is the code I used but I am not able to figure the right logic. Here's my code

bool a=1;
bool b=0;
bool c=1;
bool d=0;

uint8_t output = a|b|c|d;

printf("outupt = %X", output);

I want my output to be "1010" which is equivalent to hex "0x0A". How do I do it ??

like image 575
KBh Avatar asked Sep 13 '20 21:09

KBh


1 Answers

The bitwise or operator ors the bits in each position. The result of a|b|c|d will be 1 because you're bitwise oring 0 and 1 in the least significant position.

You can shift (<<) the bits to the correct positions like this:

uint8_t output = a << 3 | b << 2 | c << 1 | d;

This will result in

    00001000 (a << 3)
    00000000 (b << 2)
    00000010 (c << 1)
  | 00000000 (d; d << 0)
    --------
    00001010 (output)

Strictly speaking, the calculation happens with ints and the intermediate results have more leading zeroes, but in this case we do not need to care about that.

like image 153