如何将字符串转为整数?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:
- Incorrect memory allocation: You're allocating space for
MAX40instances ofInt40, but you only need a singleInt40struct. The struct'sdigitspointer is what needs to point to a dynamically allocated array ofMAX40integers. - Wrong character-to-integer conversion: Casting
str[i]directly tointgives 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). - 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

