Bytewise reading of memory: "signed char *" vs "unsigned char *" Bytewise reading of memory: "signed char *" vs "unsigned char *" c c

Bytewise reading of memory: "signed char *" vs "unsigned char *"


You should use unsigned char. The C99 standard says that unsigned char is the only type guaranteed to be dense (no padding bits), and also defines that you may copy any object (except bitfields) exactly by copying it into an unsigned char array, which is the object representation in bytes.

The sensible interepretation of this is to me, that if you use a pointer to access an object as bytes, you should use unsigned char.

Reference: http://blackshell.com/~msmud/cstd.html#6.2.6.1 (From C1x draft C99)


This is one point where C++ differs from C. Generally speaking, C onlyguarantees that raw memory access works for unsigned char; char maybe signed, and on a 1's complement or signed magnitude machine, a -0might be converted to +0 automatically, changing the bit pattern. Forsome reason (unknown to me), the C++ committee extends the guaranteessupporting transparent copy (no change in bit patterns) to char, aswell as unsigned char; on a 1's complement or signed magnitudemachine, the implementors have no choice but to make plain charunsigned, in order to avoid such side effects. (And of course, most programmers today aren't concerned by such machines anyway.)

Anyway, the end result is that older programmers, who come from a Cbackground (and maybe have actually worked on a 1's complement or asigned magnitude machine) will automatically use unsigned char. It'salso a frequent convention to reserve plain char for character datauniquely, with signed char for very small integral values, andunsigned char for raw memory, or when bit manipulation is intended.Such a rule allows the reader to distinguish between different uses(provided it is followed religiously).


In your code example it makes no difference. But if you want to display/print the value of the byte than it does (as the highest bit is interpreted differently), and unsigned char seems more suitable