If you are going to store arbitrary binary data, you should use unsigned char . This is the only data type that is guaranteed to have no complement bits according to the C standard. Each other data type may contain padding bits in its object representation (that is, one that contains all the bits of the object, not just those that determine the value) . The state of the fill bits is not defined and is not used to store values. Therefore, if you read some binary data using char , everything will be reduced to a range of char values (by interpreting only the bits of the value), but there can still be bits that are simply ignored but still exist and read memcpy . Like complementary bits in real structure objects. The unsigned char type is guaranteed to not contain. This follows from 5.2.4.2.1/2 (C99 TC2, n1124 here):
If the value of an object of type char is considered a signed integer when used in the expression, the value of CHAR_MIN must be the same as the value of SCHAR_MIN , and the value of CHAR_MAX must be the same as the value of SCHAR_MAX . Otherwise, the value of CHAR_MIN must be 0, and the value of CHAR_MAX must be the same as the value of UCHAR_MAX . UCHAR_MAX must be 2^CHAR_BIT − 1
It follows from the last sentence that there is no space left for any padding bits. If you use char as the type of your buffer, you also have an overflow problem: assigning any value explicitly to one of these elements, which is in the range of 8 bits, so you can expect such an assignment to be in order - but not in the range a char , which is equal to CHAR_MIN .. CHAR_MAX , such an overflow of transitions and leads to the implementation of certain results, including increasing signals.
Even if any of the problems associated with the above, probably will not be displayed in real implementations (this will be a very poor quality of implementation), it is best to use the correct type from the very beginning, and this is unsigned char .
For strings, however, the data type is char , which will be understood by string and print functions. Using signed char for these purposes seems like the wrong solution for me.
For more information, read this proposal , which contains a fix for the next version of the C standard, which will eventually require a signed char There are also any bits of extras. It is already included in the working paper.
Johannes Schaub - litb Mar 17 '09 at 11:53 2009-03-17 11:53
source share