Bitwise concatenation in C

佐手、 提交于 2019-12-02 03:44:26

问题


I'm trying to concatenate two binary numbers in C. So if I have 1010 and 0011 I want my result to be 10100011. I wrote a short routine that I thought would do the job:

#include <stdio.h>

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

I understand that the printed number of course is going to be in decimal, but I figured that after my bitwise operations I'd be getting the decimal equivalent of 10100011, or 163. However, my result is printed as 16169. So I guess my question is...what part of this am I not understanding here? Is it just a misunderstanding of how printf is working, or are my bitwise operations incorrect? Is it a problem to try to do this with ints?


回答1:


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



回答2:


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;
}



回答3:


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

In other words

1010 0000 + 0000 0011 = 1010 0011



来源:https://stackoverflow.com/questions/28180015/bitwise-concatenation-in-c

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