Raafat
Raafat

Reputation: 49

How I can represent the hexadecimal number?

I have an array of 4 hexadecimal elements and I want to represent these values into one hexadecimal number

i.e:

int arr[4] = {0xD4, 0x9F, 0x2E, 0x4C};   
int result = 0xD49F2E4C;   //The total number

I have tried string concatenation but the result is not the same

How to do it...

Upvotes: 2

Views: 266

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

These are not hexadecimal, decimal or anything else, despite the notation you've chosen to use for them in your source code.

They are just numbers.

So, use what you'd always use for numbers: arithmetic!

Consider that:

0xD49F2E4C = 0xD4000000 + 0x009F0000 + 0x00002E00 + 0x0000004C

So, in this case, the bitwise operators are your friends:

int result = arr[0] << 24;
result |= arr[1] << 16;
result |= arr[2] << 8;
result |= arr[3];

You should make all these things unsigned, though, to avoid surprises. In this particular instance, I'd recommend uint32_t, so that you also know that the result variable is of the right size.

Upvotes: 6

Related Questions