How can I concatenate 4 bytes to 8 in c++?

Viewed 522

How can I concatenate 4 bytes to 8?

Example:

long var1 = 0x01011; //0001 0000 0001 0001
long var2 = 0x03034; //0011 0000 0011 0100
// MAGIC...
long result = 0x10113034; //0001 0000 0001 0001 0011 0000 0011 0100
3 Answers

Use shifts and sum to combine elements. In this case, you combine 2 4-byte ints into one 8-byte long long.

unsigned int a = 0x01020304;
unsigned int b = 0x0a0b0c0e;
unsigned long long c = (((unsigned long long)a) << 32)  + b;
// c=0x010203040a0b0c0e
using ul = unsigned long;

long concat(long var1, long var2) {
    ul result  = (static_cast<ul>(var1)<<16) | static_cast<ul>(var2); 
    return static_cast<long>(result);
}

This function returns the result you want, I didn't test it extensively but intuitively it should work as sample cases.

The easiest way is probably:

By using binary operators:

unsigned long var1 = 0x1011; //0001 0000 0001 0001
unsigned long var2 = 0x3034; //0011 0000 0011 0100
unsigned long result = (var1 << 16) | var2; //Magic!: 0001 0000 0001 0001 0011 0000 0011 0100

By the way, I believe it's the fastest way of coding/computing it!

Tip: Use unsigned numbers for binary operations because it could give surprising results otherwise!

Related