c - c中有符号和无符号字符之间的区别

标签 c char signed unsigned-char

C 中有符号和无符号 char 有什么区别?当我尝试在没有 unsigned 的情况下运行以下代码时,它进入了一个无限循环,因为 signed char 的范围最大为 127 (为什么默认情况下它是签名的?)。但是当我添加 unsigned(其范围最大为 255)时,它工作正常。这是什么原因?

#include <stdio.h>

int main() {
    unsigned char x;
    x = 0;
    while (x <= 225) {
         printf("%c=%d\n", x, x);
         x = x + 1;
    }
    return 0;
}

最佳答案

C 语言中没有专门的“字符类型”。 char 是整数类型,(在这方面)与 int、short 和其他整数类型相同。

  • 都是整数类型。
  • 它们的大小相同(一个 btye)。

如果您使用数字作为字符

  • 有符号字符,它至少提供 -127 到 127 范围。 (-128 至 127 很常见)
  • Unsigned char,它至少提供 0 到 255 的范围。

来自3.9.1基本类型

Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation.

关于c - c中有符号和无符号字符之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45230345/

相关文章:

c - 图书馆管理系统采用c

c - 如何获取 *chars 并返回非整数?

ruby - 使用 ruby​​ 将存储为有符号的无符号整数转换回原始值

c - 如何在 c 中执行带符号的右移 (>>)?

c - 在微芯片的 c++/c 中解析 nmea csv

c - 如何检查和验证用户输入是两个有效选择之一

C++:从字符串中删除所有 HTML 格式?

在 C 中将 char 数组转换为 int 数字

有人可以澄清我对 C 字符串、数组与指针的混淆吗

java - 我需要帮助 : Send a list of bytes with UDP to a Server, o 它适用于有符号/无符号字节