什么是无符号字符?

2021-12-02 00:00:00 c char c++

在 C/C++ 中,unsigned char 用于什么?它与普通的 char 有何不同?

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

推荐答案

在 C++ 中,有三种不同的字符类型:

In C++, there are three distinct character types:

  • char
  • 有符号的字符
  • 无符号字符

如果您为 text 使用字符类型,请使用不合格的 char:

If you are using character types for text, use the unqualified char:

  • 它是字符文字的类型,如 'a''0'(仅在 C++ 中,在 C 中它们的类型是 int)
  • 它是组成C字符串的类型,如"abcde"
  • it is the type of character literals like 'a' or '0' (in C++ only, in C their type is int)
  • it is the type that makes up C strings like "abcde"

它也可以作为数字值计算,但未指定该值是被视为有符号还是无符号.当心通过不等式进行字符比较 - 尽管如果您将自己限制为 ASCII (0-127),那么您就很安全了.

It also works out as a number value, but it is unspecified whether that value is treated as signed or unsigned. Beware character comparisons through inequalities - although if you limit yourself to ASCII (0-127) you're just about safe.

如果您将字符类型用作数字,请使用:

If you are using character types as numbers, use:

  • signed char,它给你至少 -127 到 127 的范围.(-128 到 127 很常见)
  • unsigned char,它给你至少 0 到 255 的范围.
  • signed char, which gives you at least the -127 to 127 range. (-128 to 127 is common)
  • unsigned char, which gives you at least the 0 to 255 range.

至少",因为 C++ 标准只给出了每个数字类型需要覆盖的最小范围的值.sizeof (char) 需要为 1(即一个字节),但理论上一个字节可以是例如 32 位.sizeof 仍会报告其大小为 1 - 这意味着您可以有 sizeof (char)== sizeof (long) == 1.

"At least", because the C++ standard only gives the minimum range of values that each numeric type is required to cover. sizeof (char) is required to be 1 (i.e. one byte), but a byte could in theory be for example 32 bits. sizeof would still be report its size as 1 - meaning that you could have sizeof (char) == sizeof (long) == 1.

相关文章