Number made of 4 chars with hex

0

Iam programming in C++ and Iam comming with another "stupid" problem. If I have 4 chars like these:

char a = 0x90
char b = 0x01
char c = 0x00
char d = 0x00

when that all means hexadecimal number 0x00000190 which is 400 decimal number. How do I convert these chars to one int? I know i can do

int number = a;

but this will convert only one char to int. Could anybody help please?

c++
char
int
hex

2

You may use:

int number = (a & 0xFF)
| ((b & 0xFF) << 8)
| ((c & 0xFF) << 16)
| ((d & 0xFF) << 24);

It would be simpler with unsigned values.

1

like this

int number = ((d & 0xff) << 24) | ((c &0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff);

the << is the bit shift operator and the & 0xff is necessary to avoid negative values when promoting char to int in the expression (totally right by Jarod42)

0

This works:

unsigned char ua = a;
unsigned char ub = b;
unsigned char uc = c;
unsigned char ud = d;

unsigned long x = ua + ub * 0x100ul + uc * 0x10000ul + ud * 0x1000000ul

It is like place-value arithmetic in decimal but you are using base 0x100 instead of base 10.

If you are doing this a lot you could wrap it up in an inline function or a macro.

Note - the other answers posted so far using bitwise operations on (char)0x90 are all wrong for systems where plain char is signed, as they are forgetting that (char)0x90 is a negative value there, so after the integral promotions are applied, there are a whole lot of 1 bits on the left.

User contributions licensed under CC BY-SA 3.0