10

I've been trying to concatenate 4 hex numbers and can't seem to do it.

Example:

int a = 0x01;
int b = 0x00;
int c = 0x20;
int d = 0xF1;
//Result should be 0x010020F1

The results that I am getting using sprintf() and bitwise operations always have cut off zeros, giving me answers like 1020F1, which is much different than what I want. Anybody have a better method?

user438383
  • 5,716
  • 8
  • 28
  • 43
Mike M
  • 752
  • 1
  • 5
  • 13

1 Answers1

23

Supposing unsigned int a,b,c,d;

unsigned int result = (a<<24) | (b<<16)| (c<<8) | d;

But this is essentially implementation dependent since C++ standard only specifies minimal sizes of integers.

So for uint32_t a, b, c, d:

uint32_t result = (a<<24) | (b<<16)| (c<<8) | d;
Alex
  • 9,891
  • 11
  • 53
  • 87
  • 4
    This answer correctly uses `unsigned int`. We should emphasize the **unsigned**. If the identifiers are `int` as in the question, `a<<24` may be undefined. – Eric Postpischil Apr 25 '13 at 13:40
  • In the general case, and for maximum portability (that is, to machines with 16-bit `int`) some casts are necessary: `uint32_t result = ((uint32_t )a<<24) | ((uint32_t )b<<16)| (c<<8) | d;` – Steve Summit Aug 11 '21 at 17:30