All types except bit fields occupy an integral number of "bytes", and sizeof returns that number. An unsigned char occupies 1 "byte", so sizeof(unsigned char) always return 1. Right?
But does an unsigned char always fill a "byte", or can CHAR_BITS be less than the number of bits in a "byte" or UCHAR_MAX less than (2 to the power of CHAR_BITS) - 1? If an unsigned char can't hold all values that it's number of bits permit it too, how does copying other types with unsigned chars work?
int src = -1, dest;
size_t i;
for (i = 0; i < sizeof dest; i++) {
((unsigned char *) &dest)[i] = ((unsigned char *) &src)[i];
}
The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
If you are trying to write portable code and it matters exactly what size the memory is, use uint8_t. Otherwise use unsigned char. uint8_t always matches range and size of unsigned char and padding (none) when unsigned char is 8-bit. When unsigned char is not 8-bit, uint8_t does not exist.
A signed char is a signed value which is typically smaller than, and is guaranteed not to be bigger than, a short . An unsigned char is an unsigned value which is typically smaller than, and is guaranteed not to be bigger than, a short .
No, unsigned char
cannot have padding bits.
(C99, 6.2.6.2p1) "For unsigned integer types other than unsigned char, the bits of the object representation shall be divided into two groups: value bits and padding bits (there need not be any of the latter)."
And yes, sizeof (unsigned char)
is guaranteed to be 1
.
(C99, 6.5.3.4p3) "When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With