gpt4 book ai didi

c++ - C/C++ 为什么对二进制数据使用 unsigned char?

转载 作者:IT老高 更新时间:2023-10-28 13:57:52 25 4
gpt4 key购买 nike

真的有必要像在某些处理字符编码或二进制缓冲区的库中那样使用 unsigned char 来保存二进制数据吗?为了理解我的问题,请查看下面的代码 -

char c[5], d[5];
c[0] = 0xF0;
c[1] = 0xA4;
c[2] = 0xAD;
c[3] = 0xA2;
c[4] = '\0';

printf("%s\n", c);
memcpy(d, c, 5);
printf("%s\n", d);

printf's 都正确输出 𤭢,其中 f0 a4 ad a2 是 Unicode 代码点 U+ 的编码24B62 (𤭢) 十六进制。

甚至 memcpy 也正确地复制了 char 所持有的位。

有什么理由可以提倡使用 unsigned char 而不是 plain char

在其他相关问题中,unsigned char 被突出显示,因为它是唯一(字节/最小)数据类型,C 规范保证没有填充。但正如上面的示例所示,输出似乎不受任何填充的影响。

我已经使用 VC++ Express 2010 和 MinGW 来编译上述内容。虽然 VC 给出了警告

警告 C4309:'=':常量值截断

输出似乎没有反射(reflect)这一点。

附:这可能被标记为 Should a buffer of bytes be signed or unsigned char buffer? 的可能重复项但我的意图不同。我在问为什么应该输入 unsigned char 似乎与 char 一样正常工作的东西?

更新:引用 N3337,

第 3.9 节类型

2 For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

鉴于上述事实,并且我最初的示例是在英特尔机器上,其中 char 默认为 signed char,我仍然不相信 unsigned char 应该优先于 char

还有什么?

最佳答案

在 C 中,unsigned char 数据类型是唯一同时具有以下所有三个属性的数据类型

  • 它没有填充位,所有存储位都对数据的值有贡献
  • 从该类型的值开始的按位运算在转换回该类型时不会产生溢出、陷阱表示或未定义的行为
  • 它可以在不违反“别名规则”的情况下对其他数据类型进行别名,即通过不同类型的指针访问相同的数据将保证看到所有修改

如果这些是您正在寻找的“二进制”数据类型的属性,那么您绝对应该使用 unsigned char

对于第二个属性,我们需要一个 unsigned 类型。对于这些,所有转换都是用模算术定义的,在大多数 99% 的架构中,这里都是模 UCHAR_MAX+1256。因此,所有更宽的值到 unsigned char 的转换仅对应于截断到最低有效字节。

另外两种字符类型通常不一样。 signed char 无论如何都是有符号的,因此不适合它的值的转换没有很好的定义。 char 不固定为已签名或未签名,但在您的代码移植到的特定平台上,即使它在您的代码上未签名也可能已签名。

关于c++ - C/C++ 为什么对二进制数据使用 unsigned char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13642381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com