什么是无符号字符?

时间:2022-10-16
本文介绍了什么是无符号字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

这篇关于什么是无符号字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:为什么C和C++中main函数的类型留给用户定义? 下一条:1 字节!= 8 位的系统?

相关文章

最新文章