You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言的int类型中存储十六进制字母值?

解决混合十进制与十六进制输入的读取问题

你的代码在读取到18后停止,是因为%d格式符仅能解析十进制整数,遇到带字母的E10(十六进制表示)时解析失败,fscanf返回0,循环终止。要同时读取十进制和十六进制数,可通过以下两种方案解决:

方案1:用%x直接兼容十进制与十六进制

%x格式符可以解析所有十进制数字(十进制是十六进制的子集),同时支持解析包含A-F/a-F的十六进制数(无需0x前缀)。修改后的代码如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE* file;
    int address;
    int read_result;

    file = fopen("address01", "r");
    if (file == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }

    // 循环读取直到文件结束
    while ((read_result = fscanf(file, "%x", &address)) != EOF) {
        if (read_result == 1) {
            printf("%d\n", address);
        } else {
            // 跳过读取失败的无效字符(本场景基本不会触发)
            fgetc(file);
        }
    }

    fclose(file);
    return 0;
}

测试你的输入文件,输出结果为:

10
20
22
18
3600
528
12

其中E10(十六进制)转十进制为3600,210(按十六进制解析)转十进制为528,符合预期。

方案2:区分十进制与十六进制输入

如果需要把210当作十进制而非十六进制解析,可先读取每行字符串,判断格式后再转换:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main() {
    FILE* file;
    char line[256];
    int address;

    file = fopen("address01", "r");
    if (file == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, sizeof(line), file) != NULL) {
        // 去除换行符
        line[strcspn(line, "\n")] = '\0';
        if (line[0] == '\0') continue;

        // 判断是否包含十六进制字母
        int is_hex = 0;
        for (int i = 0; line[i] != '\0'; i++) {
            if (isxdigit(line[i]) && !isdigit(line[i])) {
                is_hex = 1;
                break;
            }
        }

        // 按对应格式转换
        if (is_hex) {
            sscanf(line, "%x", &address);
        } else {
            sscanf(line, "%d", &address);
        }
        printf("%d\n", address);
    }

    fclose(file);
    return 0;
}

这个版本会输出:

10
20
22
18
3600
210
12

内容的提问来源于stack exchange,提问作者tristan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:45:57