I want to convert char type to int type without losing the signed meaning, so i write the code in file int_test.c and it works:
#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);
}
the running result is:
(signed char)a = -2, b = -2
The compiling log is:
gcc -o int_test int_test.c int_test.c: In function ‘main’: int_test.c:9:15: warning: left shift count >= width of type [-Wshift-count-overflow] t = x | (1 << sizeof(int) * 8) - (1 << sizeof(char) * 8); \ ^ int_test.c:20:6: note: in expansion of macro ‘c2int’ b = c2int(a);
My question is: 1. Is there simple and efficient converting? 2. How to determine the signed expansion when simply convert char to int? 3. How to avoid the above warning?
Thank you.