c - 在多个 unsigned char 变量中输入十六进制值

标签 c char hex scanf unsigned

我刚刚开始使用十六进制值(用 C 语言),下面是代码:

int main(){

    unsigned char x, y, z;
    scanf("%x", &x);
    scanf("%x", &y);
    scanf("%x", &z);
    printf("val are: %x, %x, %x\n",x,y,z);
    return 0
}

在上面的代码中,为什么xy的值丢失/被覆盖,如何解决?

最佳答案

引用 C11,第 §7.21.6.2 章,对于 %x 转换说明符,(__emphasis mine_)

x

Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer.

您将参数作为指向无符号字符的指针提供。

此外,来自同一章,P10

[...] Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

因此,您的代码会调用未定义的行为。

如果参数是指向 unsigned char 的指针,则需要使用格式说明符 %hhx

关于c - 在多个 unsigned char 变量中输入十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973513/

相关文章:

从十六进制文件读取的 C 程序给出意外的输出

c - 二进制添加大型字符数组?

C fread char 代码块

c - fprintf 不会将以零结尾的十六进制数正确写入文件

使用十六进制值创建字符数组

c - 为什么我在窗口 C 编程中得到 "a.exe"而不是 "a.out"

c - 如何从处理器中获取 MPI_Gatherv 列,其中每个进程可能发送不同数量的列

c - C 中具有动态大小的用户定义类型

java - 检查回文字符串

javascript - 使用 JavaScript 基于字符串创建十六进制颜色