What is an unsigned char?

后端 未结 17 1152
借酒劲吻你
借酒劲吻你 2020-11-22 11:05

In C/C++, what an unsigned char is used for? How is it different from a regular char?

17条回答
  •  有刺的猬
    2020-11-22 11:16

    This is implementation dependent, as the C standard does NOT define the signed-ness of char. Depending on the platform, char may be signed or unsigned, so you need to explicitly ask for signed char or unsigned char if your implementation depends on it. Just use char if you intend to represent characters from strings, as this will match what your platform puts in the string.

    The difference between signed char and unsigned char is as you'd expect. On most platforms, signed char will be an 8-bit two's complement number ranging from -128 to 127, and unsigned char will be an 8-bit unsigned integer (0 to 255). Note the standard does NOT require that char types have 8 bits, only that sizeof(char) return 1. You can get at the number of bits in a char with CHAR_BIT in limits.h. There are few if any platforms today where this will be something other than 8, though.

    There is a nice summary of this issue here.

    As others have mentioned since I posted this, you're better off using int8_t and uint8_t if you really want to represent small integers.

提交回复
热议问题