Search code examples
cconcatenationbit-shift

Concatenate 2 16 bit words into one 16 bit word in c


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.


Solution

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