从 short 转换为 unsigned short 并保留位模式混淆

标签 c type-conversion data-conversion unsigned signed

我正在开展一个项目,我需要获取一系列带符号的 16 位整数、负值和正值,并将它们发送到函数以在单元测试期间进行分析。

由于不同的原因,该函数仅采用无符号 16 位整数数组,因此我需要将有符号整数存储在无符号 16 位整数数组中并完全保留相同的位模式。我正在使用 gcc (Debian 8.3.0-6) 8.3.0。

unsigned short arr[450];
unsigned short arrIndex = 0;

for (short i = -32768; i < (32767 - 100) ; i = i + 100 )
{
    arr[arrIndex] = i; 

    printf("short value is          : %d\n", i);
    printf("unsigned short value is : %d\n", arr[arrIndex]);
    arrIndex++;
}

即使我告诉 printf 打印带符号的值,我还是惊讶地发现对于那些小于零的值,位模式实际上是不同的。前几个值如下:

short value is           : -32768
unsigned short value is  : 32768

short value is           : -32668
unsigned short value is  : 32868

short value is           : -32568
unsigned short value is  : 32968

这里发生了什么,我将如何保留 i 值小于零的位模式?

最佳答案

how would I preserve the bit pattern for the values of i below zero?

对于非常常见的 2 的补码编码,以下内容就足够了。

unsigned short us = (unsigned short) some_signed_short;

BITD day with ones' complement and sign-magnitude,这还不够,代码将使用 shortunsigned shortunion .

然而,由于如何将负值 2 的补码转换为无符号,对于相同大小的类型,位模式得以保留。


the bit patterns are actually different for those values less than zero.

位模式相同。它们通过不同的转换路径进行打印,因此具有不同的文本输出。


当打印 short, unsigned short 时,最好使用 h printf 修饰符。

//printf("short value is          : %d\n", i);
//printf("unsigned short value is : %d\n", arr[arrIndex]);
printf("short value is          : %hd\n", i);
printf("unsigned short value is : %hu\n", arr[arrIndex]);

关于从 short 转换为 unsigned short 并保留位模式混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61620480/

相关文章:

从函数返回时的 C++ 基本类型降级

c++ 将 vector<pair<double,double>> 转换为 double*, double*?

c# - 接口(interface)、继承、隐式运算符和类型转换,为什么会这样?

xml - 使用 powershell 将带有命名空间的 XML 转换为 CSV

c - 为什么在使用 realloc() 时出现段错误?

c - 一次从文件中读取两行

c# - 将字符串转换为带小数点分隔符后 2 位的 double

将 *char 转换为 int 时出现 C++ 错误

c - fgetc while 循环内的段错误

c - C 中的位,如何访问 C float 中的底层位?