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

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

    Is it really necessary to use unsigned char to hold binary data as in some libraries which work on character encoding or binary buffers?

    "really" necessary? No.

    It is a very good idea though, and there are many reasons for this.

    Your example uses printf, which not type-safe. That is, printf takes it's formatting cues from the format string and not from the data type. You could just as easily tried:

    printf("%s\n", (void*)c);
    

    ... and the result would have been the same. If you try the same thing with c++ iostreams, the result will be different (depending on the signed-ness of c).

    What reasoning could possibly advocate the use of unsigned char instead of a plain char?

    Signed specifies that the most significant bit of the data (for unsigned char the 8-th bit) represents the sign. Since you obviously do not need that, you should specify your data is unsigned (the "sign" bit represents data, not the sign of the other bits).

提交回复
热议问题