繁体   English   中英

将char类型(非ascii)转换为int

[英]convert char type(not ascii) to int

我想将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:警告:左移计数> =类型[-Wshift-count-overflow]的宽度t = x | (1 << sizeof(int)* 8)-(1 << sizeof(char)* 8); \\ ^ int_test.c:20:6:注意:在宏'c2int'的扩展中b = c2int(a);

我的问题是: 1.是否有简单有效的转换方法? 2.仅将char转换为int时如何确定带符号的扩展? 3.如何避免以上警告?

谢谢。

您正在执行手动的显式符号转换。 不要那样做 代替:

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

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

是否要扩展符号? 如果要扩展符号,则必须先经过签名的 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
  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. 如何避免以上警告?

    确保移位小于位宽。
    避免移入符号位。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM