C/C++ Why to use unsigned char for binary data?

后端 未结 8 1069
-上瘾入骨i
-上瘾入骨i 2020-12-07 10:27

Is it really necessary to use unsigned char to hold binary data as in some libraries which work on character encoding or binary buffers? To make sense of my que

8条回答
  •  执笔经年
    2020-12-07 11:02

    You'll get most of your problems when comparing the contents of individual bytes:

    char c[5];
    c[0] = 0xff;
    /*blah blah*/
    if (c[0] == 0xff)
    {
        printf("good\n");
    }
    else
    {
        printf("bad\n");
    }
    

    can print "bad", because, depending on your compiler, c[0] will be sign extended to -1, which is not any way the same as 0xff

提交回复
热议问题