在C中将两个数字转换为一个

时间:2012-10-09 09:59:33

标签: c numbers

新手问题; 我有两个二进制数;比如说; 0b11和0b00。如何合并这两个数字,以便得到0b1100(即将它们放在彼此旁边以形成一个新数字)

2 个答案:

答案 0 :(得分:5)

使用按位移位和或运算符:

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 */

答案 1 :(得分:2)

左移<<和按位OR |

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

注意:

  • 但是不需要OR,因为在这种情况下a为0。
  • 移位运算符中的2表示“向左移两位”。向右移动是>>运算符。