Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise concatenation in C

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?

like image 337
Roshan Krishnan Avatar asked Jan 09 '23 00:01

Roshan Krishnan


2 Answers

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
like image 58
Rizier123 Avatar answered Jan 14 '23 09:01

Rizier123


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;
}
like image 31
VolAnd Avatar answered Jan 14 '23 07:01

VolAnd