long int to char:C中的奇怪输出

今天春*_*天春天 0 c char long-integer

我有以下char序列:

    char* input = "3243f6a8885a308d313198a2e0370734";
Run Code Online (Sandbox Code Playgroud)

然后我尝试从前两个字符中提取并将其input存储为如下数字:

char state_col[9];
char state_col_t[3];

memcpy(state_col, input, 8);
state_col[8] = 0;
state_col_t[0] = state_col[0]; state_col_t[1] = state_col[1]; state_col_t[2] = 0;
long int value = strtol(state_col_t, &endptr, 16);
char c_value = value;
Run Code Online (Sandbox Code Playgroud)

当我尝试打印出结果时:

printf("%x %x", c_value, value);
Run Code Online (Sandbox Code Playgroud)

我得到这个(例如):

32 32

43 43

fffffff6 f6

ffffffa8 a8

它似乎与值> 0x80有关.想法?

Mik*_*CAT 5

是否char签名是实现定义的,如何转换太大而不是有符号整数的整数也是实现定义的.

你应该使用unsigned char或uint8_t为c_value.

请注意,您必须包含inttypes.h(或stdint.h)uint8_t.

顺便说一句,您通过传递具有错误类型的数据来调用未定义的行为printf().正确的格式说明符用于打印具有long int十六进制类型的数据%lx.

使用%xfor char,unsigned char或者uint8_t应该可以归功于整数提升.