Kevin Baker
Kevin Baker

Reputation: 139

How to read hex characters from an array backwards and convert to an int

Say I have an array such as:

unsigned char data[2] = { 0x00, 0x20 };

and I want to get the integer value of all the hex values read backwards, so 0200 would be the hex value which would be 512 in decimal. How would you go about doing this in c++? I read other posts about using sstream but I am not sure how I would get the stream to read the values backwards.

Upvotes: 0

Views: 104

Answers (1)

Adam Leggett
Adam Leggett

Reputation: 4113

First thing - these aren't hex or decimal values. They become that when you print them. They are binary. sstream deals with string streams. Nothing here refers to strings of text.

Second thing - what you shouldn't do. Don't create a union with unsigned short [] or a reinterpret_cast, and then a bit shift. It's unclean, endian dependent, and if you have a lot of data and are performance critical there are better ways. If not:

    i = 0;
    while(i + 1 < length)
    {
        uint16_t value;
        value = (uint16_t)data[i++];
        value |= (uint16_t)data[i++] << 8;
        ...
    }

Upvotes: 1

Related Questions