我想将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);
}
Run Code Online (Sandbox Code Playgroud)
运行结果是:
(signed char)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;
}
Run Code Online (Sandbox Code Playgroud)
这确实为您签署了扩展名,并且不会产生警告.
| 归档时间: |
|
| 查看次数: |
431 次 |
| 最近记录: |