Search code examples
c++castinghexshort

Issues converting Hex to Short getting the wrong value


I have a function that converts 2 char values into an unsigned short:

unsigned short ToShort(char v1, char v2) {
    unsigned short s = ((v1 << 8) | v2);
    return s;
}

It works most of the time, but occasionally I get a number that is not correct. As we can see, some of the numbers in my output file are around 65000 when they should be a low number. This happens for large numbers as well.

One the left, we have good output. On the right, I have my own output.

image

Both outputs use the same input. Bytes are read from a file and stored into an array of chars. This array contained short values. You can see the error when some of the values are put into a short.


Solution

  • char gets a sign extension when OR'ed. Instead of v2 you could do:

    (v2 & 0xFF)
    

    unsigned char would be feasible, too.