新手问题; 我有两个二进制数;比如说; 0b11和0b00。如何合并这两个数字,以便得到0b1100(即将它们放在彼此旁边以形成一个新数字)
答案 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 */
注意:
a
为0。2
表示“向左移两位”。向右移动是>>
运算符。