James
James

Reputation: 301

Converting two numbers into one in C

newbie question; I have two binary numbers; say for example; 0b11 and 0b00. How can I combine the two numbers so that I get 0b1100 (i.e. place them right next to each other to form a new number)

Upvotes: 2

Views: 439

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409364

With bitwise shift and or operators:

unsigned int a = 0x03;  /* Binary 11 (actually binary 00000000000000000000000000000011) */
unsigned int b = 0x00;  /* Binary 00 */

/* Shift `a` two steps so the number becomes `1100` */
/* Or with the second number to get the two lower bits */
unsigned int c = (a << 2) | b;

/* End result: `c` is now `1100` binary, or `0x0c` hex, or `12` decimal */

Upvotes: 6

Bart Friederichs
Bart Friederichs

Reputation: 33533

Shifting left << and bitwise OR |:

int a = 0;             /* 0b00 */
int b = 3;             /* 0b11 */
int c = (b << 2) | a;  /* 0b1100 */

Notes:

  • The OR is not needed though, because a is 0 in this case.
  • The 2 in the shift operator means "shift two bits to the left". Shifting right is the >> operator.

Upvotes: 2

Related Questions