Array manipulation

Hi Everyone!!

I have an array that has hexadecimal values in it as it's elements:

unsigned char arr = [0x81 0x78 0xAB]

I was wondering how can I add the values in that array to produce a hex variable:

hex= 0x8178AB.

I then want to be able to do mathematical operations on this variable like division.
I went through different posts in other forums and I saw commands like "itoa". But the problem with that is the fact that the variable is stored as a string and I won't be able to do mathematical operations on it like a hex variable.

I would appreciate any help. :slight_smile:

If it was a normal array,
byte arr = {0x81, 0x78, 0xAB,}
I’d say just do this
unsigned long result = (arr[0]<<16) | (arr[1]<< 8 ) | arr[2];
to yield 0x008178AB
So first step might be converting your char string to real hex #s.

CrossRoads:
If it was a normal array,
byte arr = {0x81, 0x78, 0xAB,}
I’d say just do this
unsigned long result = (arr[0]<<16) | (arr[1]<< 8 ) | arr[2];
to yield 0x008178AB
So first step might be converting your char string to real hex #s.

You might need to explicitly cast arr[0] and arr[1] in that, since they’ll be shifted outside of what a char can hold and might end up with all 0s. I don’t have my board with me so I can’t test it right now.

You might need to explicitly cast arr[0] and arr[1]

Could you please explain how you would go about achieving that?

Could you please explain how you would go about achieving that?

unsigned long result = ((unsigned long)arr[0]<<16) | ((unsigned long)arr[1]<< 8 ) | arr[2];

Cheers!!!
It is producing the correct result.

Thanks to you all. :slight_smile:

Just out of curiosity, if my array had 50 elements instead of 3, how could I achieve the same result? Is there a limit to the number of elements that I can put into the variable “result”?

Just out of curiosity, if my array had 50 elements instead of 3, how could I achieve the same result?

You couldn’t, you’re limited by the size of the variable, in your case to four bytes.

Arduino does support the type uint64_t or unsigned long long == 8 bytes
but it is seldom used and quite slow...