The chef
The chef

Reputation: 85

combine multiple chars to an int

I have four unsigned chars, each containing a byte, that I want to combine together to form a single int32_t, where the bytes come one after another.

       unsigned char x1 = 0b11100111;
       unsigned char x2 = 0b00010101;
       unsigned char x3 = 0b10000110;
       unsigned char x4 = 0b00001111;

With the four chars above the int32_t should have a binary representation of 0b11100111000101011000011000001111.

How can this be done in c?

Upvotes: 4

Views: 3912

Answers (2)

savram
savram

Reputation: 580

You could do it like follows:



    #include <stdint.h>
    #include <stdio.h>

    int main() {
      unsigned char x1 = 0b11100111;
      unsigned char x2 = 0b00010101;
      unsigned char x3 = 0b10000110;
      unsigned char x4 = 0b00001111;
      int32_t x5 = x1;
      x5 <<= 8;
      x5 |= x2;
      x5 <<= 8;
      x5 |= x3;
      x5 <<= 8;
      x5 |= x4;

      printf("%d", x5);

    }

Upvotes: 0

dbush
dbush

Reputation: 223689

You can do this with a series of shifts and bitwise OR operations:

uint32_t x = 0;
x |= (uint32_t)x1 << 24;
x |= (uint32_t)x2 << 16;
x |= (uint32_t)x3 << 8;
x |= (uint32_t)x4;

Since the bytes are unsigned, you should use an uint32_t for the destination, otherwise you run into implementation defined behavior if the high order bit is set.

Upvotes: 4

Related Questions