1

I am trying to get the Least significant 4 bits of one word and the most significant 12 bits of another word and concatenate them into a single word. I am working in C, which I haven't worked with much in the past.

int a;
int b;
int c;
int a_masked;
int b_masked;
a = 0x1234;
b = 0xABCD;

a_masked = a & 0X000F;
b_masked = b & 0xFFF0;

c = ((a_masked << 12) || b_masked >> 4);

printf("%d", c);

C should be 4ABC, but my result is 1.

ChrisD
  • 35
  • 3
  • 1
    Note: `%x` and `%X` will print an `int` in hexadecimal, which will make it easier to see if your bitwise operation succeeded. – Govind Parmar Mar 18 '21 at 20:28
  • 1
    Apart from the `||`, watch it when shifting _signed_ values (i.e. probably don't do that): https://stackoverflow.com/q/7622/6372809 – ilkkachu Mar 18 '21 at 21:18

1 Answers1

3

|| operator, which you used, is a logical OR operator and it returns 0 or 1.

You should use a bitwise OR operator | (one vertical line, not two).

MikeCAT
  • 73,922
  • 11
  • 45
  • 70