問題描述
在 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 isint
) - 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
.
這篇關于什么是無符號字符?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!