Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the unsigned char type have padding bits and/or unused values?

Tags:

c

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];
}
like image 632
potrzebie Avatar asked Dec 18 '12 09:12

potrzebie


People also ask

How many bits is an unsigned char?

The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.

What is an unsigned char?

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.

Is unsigned char same as uint8?

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.

What's the difference between unsigned and signed char?

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 .


1 Answers

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."

like image 68
ouah Avatar answered Nov 06 '22 02:11

ouah