将char类型(不是ascii)转换为int

时间:2016-09-14 11:52:24

标签: c type-conversion

我想将char类型转换为int类型而不会丢失带符号的含义, 所以我在文件int_test.c中编写代码并且它可以工作:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

#define c2int(x) \
({                         \
        int t;             \
        if (x > 0x80)      \
                t = x | (1 << sizeof(int) * 8) - (1 << sizeof(char) * 8); \
        else               \
                t = x;     \
        t;                 \
 })

int main()
{
        uint8_t a = 0xFE;
        int b;

        b = c2int(a);

        printf("(signed char)a = %hhi, b = %d\n", a, b);

        exit(EXIT_SUCCESS);
}

运行结果是:

  

(签名字符)a = -2,b = -2

编译日志是:

  

gcc -o int_test int_test.c int_test.c:在函数'main'中:   int_test.c:9:15:警告:左移计数&gt; =类型的宽度   [-Wshift计数溢出]       t = x | (1&lt;&lt; sizeof(int)* 8) - (1&lt; sizeof(char)* 8); \                  ^ int_test.c:20:6:注意:在扩展宏'c2int'b = c2int(a);

我的问题是: 的 1。有简单有效的转换吗? 2.简单地将char转换为int时如何确定签名扩展? 3.如何避免上述警告?

谢谢。

3 个答案:

答案 0 :(得分:5)

您正在进行手动,明确的符号转换。不要那样做。代替:

static int c2int(unsigned char x)
{
    return (signed char)x;
}

这会为您签名扩展,并且不会产生警告。

答案 1 :(得分:1)

你想要签名延期吗?如果您需要签名扩展,则必须首先通过签名 char。如果没有,那么只需使用赋值或初始化隐式转换:

unsigned char x = 0xfe;
int y = (signed char) x;
int z = x;
printf("x = %hhx, y = %08x, z = %08x\n", x, y, z);

上面的代码应该打印

x = fe, y = fffffffe, z = 000000fe

答案 2 :(得分:0)

  1. 是否有简单有效的转换?

    // To convert a value to char and then to int
    // As a function or macro
    #define c2int(x) ((int)(char)(x))
    int c2int(char x) { return x; }
    
    // To convert a value to signed char and then to int
    #define c2int(x) ((int)(signed char)(x))
    int c2int(signed char x) { return x; }
    
  2. 如何在将char转换为int时确定签名扩展?

    无需特殊代码,请参见上文。 C为你做这件事。

  3. 如何避免上述警告?

    保证换档小于位宽    避免转入符号位。

相关问题