c - 将 char 转换为 int 时出现意外行为

标签 c type-conversion

我在将 char 转换为 unsigned int 时遇到意外行为。有时剩余位用 0 填充,有时用 1 填充。

在 gcc 4.9.2 上测试的简单程序

unsigned int test_1 = 0x01;
unsigned int test_2 = (char)(0x01);
unsigned int test_3 = 0xc3;
unsigned int test_4 = (char)(0xc3);

输出为

00000000 00000000 00000000 00000001 
00000000 00000000 00000000 00000001 
00000000 00000000 00000000 11000011 
11111111 11111111 11111111 11000011

我期望“空白”位填充 0 而不是 1。

预期输出:

00000000 00000000 00000000 00000001 
00000000 00000000 00000000 00000001 
00000000 00000000 00000000 11000011 
00000000 00000000 00000000 11000011
<小时/>

完整代码如下:

#include "stdio.h"

#define binary_p( x ) printBits(sizeof(x),&x)

void printBits(size_t const size, void const * const ptr)
{
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }

            printf(" ");
    }
     puts("");
}

int main(int argc, char *argv[])
{
    unsigned int test_1 = 0x01;
    unsigned int test_2 = (char) (0x01);
    unsigned int test_3 = 0xc3;
    unsigned int test_4 = (char) (0xc3);

    binary_p(test_1);
    binary_p(test_2);
    binary_p(test_3);
    binary_p(test_4);

    return 0;
}

最佳答案

在这种情况下:

unsigned int test_3 = 0xc3;

常量0xc3的类型为int。它的值 (195) 位于 int 的正范围内,因此当它通过赋值转换为 unsigned int 时,它会保留该值。

对于本例:

unsigned int test_4 = (char)(0xc3);

该值首先被转换为char。假设 char 是 8 位,并且 2 的补码表示用于负数,则该表示落入负数范围 (-61)。因此,当转换为更大的类型时,添加的额外位将被设置为 1,以保留相同的负值。

关于c - 将 char 转换为 int 时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814890/

相关文章:

c - 通过 const 限定符保护变量的数据是没有用的!!!?

c - 字符串文字 : Where do they go?

c - C 中的字符串不以空字符结尾

c# - 如何在 C# 中将 Decimal 转换为 Double?

Haskell:从/到整数转换的冗长可以更简洁吗?

python - 如何将带符号整数值的字符串转换为带符号整数?

来自谷歌电子表格的 JSON 数据

c - 如何使用 GDB(或其他程序)获得堆栈的总体概述?

c - 并行化 for 循环

c++ - 无法读取二进制编码的十六进制值