5

I have a hex value stored in a two byte array:

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

How can I convert this to a decimal value?

2
  • 1
    It is one of those nights... Feel free to give as much offense as possible as I deserve it. I am not sure why but the closer finals get the more I have horrible horrible lapses in "thinking". For some reason I was thinking there is more to it than that. I had my self convinced that it was much more complicated... Commented Apr 26, 2011 at 0:23
  • 1
    @Mitch Wheat: Don't worry about it. You comment actually made me pause for a second and realize that I did know the answer to my question. As I get closer to starting my coop I find my self horrified of making mistakes like this and looking rather dumb. It is probably good to be reminded that making mistakes and/or not remembering something of the top of my head is doomed to happen and not the end of the world. Commented Apr 26, 2011 at 0:35

3 Answers 3

7

You can use (bitwise operation)

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

or (simple math)

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

Sign up to request clarification or add additional context in comments.

Comments

0

Depends on endian-ness, but something like this?

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

2 Comments

The "depends on what kind of Indian you've got" part's true.
Some reasons as to why this is not correct: First you are shifting the first char by 16 bits instead of 8 bits. A char is typically 8 bits. Second you are ANDing the two parts, you need to OR them. By shifting hex[0] over you are leaving the first 16 bits as zeros and when ANDed with hex[1] you will effectively remove hex[1]. (Since zero anded is always zero) Thanks for the input though!
0

This isn't an efficient way at least I do not think it is, but it would work in all situations regardless of size of the array and will easily convert to b.

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

In the above example it the variable "value" will have a value of 16,843,009. Which is equivalent to if you had done the below.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.