Convert hex value to char array to integer value

I have a hex value stored in an array with two bytes:

unsigned char hex[2] = {0x02, 0x00}; 

How can I convert this to a decimal value?

+4
source share
3 answers

You can use (bitwise operation)

int b = (hex[0] << 8) | hex[1];

or (simple math)

int b = (hex[0] * 0x100) + hex[1];

+6
source

Depends on the limb, but something like this?

 short value = (hex[0] << 16) & hex[1]; 
0
source

This is not an efficient way, at least I don’t think so, but it will work in all situations regardless of the size of the array and is easily converted to b.

 __int8 p[] = {1, 1, 1, 1, 1}; //Let say this was the array used. int value = sizeof(p); //Just something to store the length. memcpy(&value, &p, value > 4 ? 4 : value); //It okay to go over 4, but might as well limit it. 

In the above example, the variable "value" will have a value of 16 843 009. This is equivalent if you did it below.

 int value = p[0] | p[1] << 0x8 | p[2] << 0x10 | p[3] << 0x18; 
0
source

All Articles