-17 != 0xef.
Sometimes we omit the very basic. This morning, I was looking at this code:
char c1, c2, c3;
....
if (c1== 0xef && c2== 0xbb && c3== 0xbf)
{...}
I was reading a file, checking the first three bytes and verifing whether the file is a UTF-8 encoding file with signature. In the watch pane of Visual Studio, I saw the value of c1 was 0xef, value of c2 was 0xbb and value of c3 was 0xbf. But the if statement returned me false. It turns out that c1, c2 and c3 are all char type, which has a range of -128 ~ 127. Even if c1 == -17 and -17 has the same bit string, 11101111, as 0xef, c1 != 0xef. When I changed c1, c2 and c3 to be type of unsigned char or BYTE, which have a range of 0 ~ 255, everything worked fine.
char c1, c2, c3;
....
if (c1== 0xef && c2== 0xbb && c3== 0xbf)
{...}
I was reading a file, checking the first three bytes and verifing whether the file is a UTF-8 encoding file with signature. In the watch pane of Visual Studio, I saw the value of c1 was 0xef, value of c2 was 0xbb and value of c3 was 0xbf. But the if statement returned me false. It turns out that c1, c2 and c3 are all char type, which has a range of -128 ~ 127. Even if c1 == -17 and -17 has the same bit string, 11101111, as 0xef, c1 != 0xef. When I changed c1, c2 and c3 to be type of unsigned char or BYTE, which have a range of 0 ~ 255, everything worked fine.

0 Comments:
Post a Comment
<< Home