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

后端 未结 8 1091
-上瘾入骨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:13

    Bytes are usually intended as unsigned 8 bit wide integers.

    Now, char doesn't specify the sign of the integer: on some compilers char could be signed, on other it may be unsigned.

    If I add a bit shift operation to the code you wrote, then I will have an undefined behaviour. The added comparison will also have an unexpected result.

    char c[5], d[5];
    c[0] = 0xF0;
    c[1] = 0xA4;
    c[2] = 0xAD;
    c[3] = 0xA2;
    c[4] = '\0';
    c[0] >>= 1; // If char is signed, will the 7th bit go to 0 or stay the same?
    
    bool isBiggerThan0 = c[0] > 0; // FALSE if char is signed!
    
    printf("%s\n", c);
    memcpy(d, c, 5);
    printf("%s\n", d);
    

    Regarding the warning during the compilation: if the char is signed then you are trying to assign the value 0xf0, which cannot be represented in the signed char (range -128 to +127), so it will be casted to a signed value (-16).

    Declaring the char as unsigned will remove the warning, and is always good to have a clean build without any warning.

提交回复
热议问题