Bitwise concatenation in C

三世轮回 提交于 2019-12-01 23:54:36

You forgot the prefix 0b, so this should work for you:

#include <stdio.h>

int main() {

    int first = 0b1010;
              //^^v See here
    int second = 0b0011;
    int result = (first << 4) | second;
    printf("%d", result);

    return 0;

}

Output:

163

In your examle the 'binary numbers' aren't binary numbers. The first one is a normal decimal number (1010) and the second one is a octal number, because of the prefix 0 so in decimal the second number was: 9

So what happened is:

1010 -> decimal
0011 -> octal

First number:

     11 1111 0010      
----------------- << 4
11 1111 0010 0000

Second number (->decimal->binary):

  octal    decimal       binary
  0011  ->    9     ->  0000 1001

And your calculation:

11 1111 0010 0000   first number
             1001   second number
----------------- |
11 1111 0010 1001 = 16169

If you do not want to be dependent on the new standard, you can learn a simple rule overextension binary system in hexadecimal

HEX  BIN
 00  0000
 01  0001
 02  0010
 03  0011
 04  0100
 05  0101
 06  0110
 07  0111
 08  1000
 09  1001
 0A  1010
 0B  1011
 0C  1100
 0D  1101
 0E  1110
 0F  1111
 10 10000

So you program may be rewritten as:

#include <stdio.h>

int main(void) {
    int first = 0xA;  // 1010;
    int second = 0x3; // 0011;
    int result = (first << 4) | second;
    printf("%X", result);
    return 0;
}

Cant you also return (0xA<<4) + 0x3.

In other words

1010 0000 + 0000 0011 = 1010 0011

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!