Home > Mobile >  Issues converting Hex to Short getting the wrong value
Issues converting Hex to Short getting the wrong value

Time:02-13

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.

CodePudding user response:

Char gets a sign extension when orred. Instead of v2 you could do

(v2 & 0xFF)

Unsigned char would be feasible too.

  • Related