Majiick
Majiick

Reputation: 253

Comparing unsigned char with signed char

I have an array of unsigned char and an array of just char. I want to compare both of them so see if they're the same. Sometimes the comparison fails even when the bits are the same.

I know I can use memcmp(), but I'm just curious on how to do it manually.

char* arr1;
unsigned char* arr2;
...
if (arr1[i] != arr2[i]) { //move zero extend vs move sign extend
        std::bitset<8> x(arr1[i]);
        std::bitset<8> y(arr2[i]);

        std::cout << x << " " << y << std::endl; //The bits are the same.
}

Even though the char values might be the same, the comparison will say that they're different because arr1 gets moved into a register using a movzx(move zero extend) while arr2 gets moved into a register using a movsx(move sign extend).

This leads to problems with numbers such as 0x90 where the most significant bit is a one. Therefore a movsx so a 32-bit register will result in the value 0xFFFFFF90 while a movzx will result in the value 0x90 and the cmp instruction will say that they're different.

Upvotes: 1

Views: 2150

Answers (1)

Majiick
Majiick

Reputation: 253

Alright, you just need to cast them both to a (char) when comparing.

Upvotes: 1

Related Questions