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

如何将字符串转为整数?40位十六进制字符串转Int40结构体求助

Hey there, let's work through this problem step by step. Your current code has a few critical issues that are keeping it from working correctly, so we'll fix those first, then implement the proper way to parse that 40-digit hex string into your Int40 structure.

First, Let's Spot the Problems in Your Existing Code

Your current approach has three key mistakes:

  1. Incorrect memory allocation: You're allocating space for MAX40 instances of Int40, but you only need a single Int40 struct. The struct's digits pointer is what needs to point to a dynamically allocated array of MAX40 integers.
  2. Wrong character-to-integer conversion: Casting str[i] directly to int gives you the ASCII value of the character (e.g., '0' becomes 48, not 0). You need to convert each hex character to its actual numeric value (0-15).
  3. No reverse storage: The struct requires digits to be stored in reverse order, but you're copying characters in the same order as the string.

Correct Implementation of parseString

First, make sure you define MAX40 as 40 (since we're dealing with a 40-digit hex number):

#define MAX40 40

Here's the fixed parseString function, with proper memory management, character conversion, and reverse storage:

#include <stdlib.h>
#include <ctype.h> // For tolower()

typedef struct Int40 {
    int *digits;
} Int40;

Int40 *parseString(char *str) {
    // Allocate memory for the Int40 struct itself
    Int40 *value = malloc(sizeof(Int40));
    if (!value) {
        return NULL; // Handle memory allocation failure
    }

    // Allocate memory for the digits array (40 integers)
    value->digits = malloc(sizeof(int) * MAX40);
    if (!value->digits) {
        free(value); // Clean up the struct if digits allocation fails
        return NULL;
    }

    // Iterate through the string, storing digits in reverse order
    for (int i = 0; i < MAX40; i++) {
        // Get the character from the string in reverse order
        char c = str[MAX40 - 1 - i];
        int digit;

        // Convert hex character to its numeric value
        if (isdigit(c)) {
            digit = c - '0'; // '0' to '9' become 0-9
        } else {
            c = tolower(c); // Handle uppercase/lowercase letters uniformly
            if (c >= 'a' && c <= 'f') {
                digit = 10 + (c - 'a'); // 'a'-'f' become 10-15
            } else {
                // Invalid hex character: clean up and return error
                free(value->digits);
                free(value);
                return NULL;
            }
        }

        value->digits[i] = digit;
    }

    return value;
}

How to Use This in main

Here's an example main function to test the parser, including memory cleanup to avoid leaks:

#include <stdio.h>

int main() {
    // Example 40-digit hex string (replace with your actual input)
    char hexStr[MAX40 + 1] = "0123456789abcdef0123456789abcdef01234567";
    Int40 *p = parseString(hexStr);

    if (!p) {
        printf("Failed to parse the hex string (invalid characters or memory issue)\n");
        return 1;
    }

    // Verify the result: print the digits in reverse storage order
    printf("Stored digits (reverse of input string):\n");
    for (int i = 0; i < MAX40; i++) {
        printf("%d ", p->digits[i]);
    }
    printf("\n");

    // Always free allocated memory to avoid leaks
    free(p->digits);
    free(p);

    return 0;
}

Key Details on Hex String to Integer Conversion

Let's break down the character-to-integer logic since that's a core part of your question:

  • Numeric characters ('0'-'9'): Subtract the ASCII value of '0' from the character. Since '0' is ASCII 48, '5' (ASCII 53) minus '0' gives 5, which is the correct numeric value.
  • Alphabetic characters ('a'-'f' or 'A'-'F'): Convert to lowercase first, then subtract 'a' (ASCII 97) and add 10. For example, 'F' becomes 'f', 'f'-'a' is 5, plus 10 gives 15, which is the hex value of F.
  • Error handling: If we encounter a character that's not a valid hex digit, we clean up any allocated memory and return NULL to signal failure.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:28:32