【发布时间】:2017-01-22 05:17:10
【问题描述】:
我想将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
我的问题是: 1。有没有简单高效的转换? 2. char转int时如何判断有符号展开式? 3、如何避免上述警告?
谢谢。
【问题讨论】:
-
如果您的
char已签名,请执行以下操作:(int)c如果未签名,“签名含义”是什么意思?uint8_t也不是char,请说明你到底需要什么。 -
uint8_t a中没有符号位可以丢失。b = a;有什么问题?
标签: c type-conversion