Chars 在-128 和 127 之间是否正常?
Is it Normal For Chars to be Between -128 and 127?
要找出标准 8 位字符的整数值的 运行ge,我 运行 以下代码:
int counter = 0;
for (int i = -300; i <= 300; i++)
{
char c = static_cast<char> (i);
int num = static_cast<int> (c);
if (num == i)
{
counter ++;
}
else
{
cout << "Bad: " << i << "\n";
}
}
cout << "\n" << counter;
我最终看到计数器的值为 256,这是有道理的。但是,在 "Bad" 数字列表(即字符不存储的数字)中,我发现最大的 Bad 负数是 -129,而最小的 Bad 正数是 128。
从这个测试来看,chars 似乎只存储从 -128 到 127 的整数值。这个结论是正确的,还是我遗漏了什么?因为我一直认为字符存储的是 0 到 255 之间的整数值。
虽然实现已定义,但在大多数情况下 - 是的,这是正常的,因为您的实现将 char
定义为 signed char
。您可以使用 CHAR_MIN
和 CHAR_MAX
宏打印出类型 char
:
的最小值和最大值
#include <iostream>
#include <cstdint>
int main() {
std::cout << CHAR_MIN << '\n';
std::cout << CHAR_MAX << '\n';
}
或使用 std::numeric_limits class 模板:
#include <iostream>
#include <limits>
int main() {
std::cout << static_cast<int>(std::numeric_limits<char>::min()) << '\n';
std::cout << static_cast<int>(std::numeric_limits<char>::max()) << '\n';
}
至于0..255范围即unsigned char
类型。最小值为 0
,最大值应为 255
。可以使用以下方式打印出来:
std::cout << UCHAR_MAX;
可以通过以下方式检查类型是否已签名:
std::numeric_limits<char>::is_signed;
摘自 char type 参考文献:
char
- type for character representation which can be most
efficiently processed on the target system (has the same
representation and alignment as either signed char
or unsigned
char
, but is always a distinct type).
要找出标准 8 位字符的整数值的 运行ge,我 运行 以下代码:
int counter = 0;
for (int i = -300; i <= 300; i++)
{
char c = static_cast<char> (i);
int num = static_cast<int> (c);
if (num == i)
{
counter ++;
}
else
{
cout << "Bad: " << i << "\n";
}
}
cout << "\n" << counter;
我最终看到计数器的值为 256,这是有道理的。但是,在 "Bad" 数字列表(即字符不存储的数字)中,我发现最大的 Bad 负数是 -129,而最小的 Bad 正数是 128。
从这个测试来看,chars 似乎只存储从 -128 到 127 的整数值。这个结论是正确的,还是我遗漏了什么?因为我一直认为字符存储的是 0 到 255 之间的整数值。
虽然实现已定义,但在大多数情况下 - 是的,这是正常的,因为您的实现将 char
定义为 signed char
。您可以使用 CHAR_MIN
和 CHAR_MAX
宏打印出类型 char
:
#include <iostream>
#include <cstdint>
int main() {
std::cout << CHAR_MIN << '\n';
std::cout << CHAR_MAX << '\n';
}
或使用 std::numeric_limits class 模板:
#include <iostream>
#include <limits>
int main() {
std::cout << static_cast<int>(std::numeric_limits<char>::min()) << '\n';
std::cout << static_cast<int>(std::numeric_limits<char>::max()) << '\n';
}
至于0..255范围即unsigned char
类型。最小值为 0
,最大值应为 255
。可以使用以下方式打印出来:
std::cout << UCHAR_MAX;
可以通过以下方式检查类型是否已签名:
std::numeric_limits<char>::is_signed;
摘自 char type 参考文献:
char
- type for character representation which can be most efficiently processed on the target system (has the same representation and alignment as eithersigned char
orunsigned char
, but is always a distinct type).