-4
unsigned char num;
unsigned char b0=1;
unsigned char b1=0;
unsigned char b2=1;

How to assign num to b2b1b0? If we print num in binary at the end, it should be 101.

Ichihara26
  • 47
  • 6

1 Answers1

0

Assuming b0, b1, and b2 are all bits within the num variable, and assuming little-endianness:

num = 1 | 4;

If you really needed to use the b* variables (I'm assuming you don't), You could do this:

unsigned char b0 = 1U;
unsigned char b1 = 2U;
unsigned char b2 = 4U;
unsigned char num = b0 | b2;
djhaskin987
  • 9,741
  • 4
  • 50
  • 86
  • Can you explain what's 1 | 4 in c? Thanks – Ichihara26 Nov 07 '14 at 22:33
  • The number 1 *bitwise-or*'ed with the number 4, or, in binary, '`1` or `100`' -- which equals `101`. – djhaskin987 Nov 07 '14 at 22:36
  • `1 | 4` indicates a bitwise OR operation between the two values. Written in binary as three bits each, this is `001 | 100`. The OR operation makes a new value, keeping the `1` bits wherever they occur. In this case the result is `101` which is 5 in decimal. Hopefully that makes sense of `1 | 4 = 5`. Coincidentaly the result here is the same as adding them would be, but can you see that `1 | 5 = 5` too? – Weather Vane Nov 07 '14 at 22:40
  • b* variables are unknown. b* are the LSBs from 3 different random numbers – Ichihara26 Nov 07 '14 at 22:48