这可能已经在这里被问过一百万次了,但这是一个简单的通用解决方案int
,通过无论如何在您的代码中使用):tolower()
strlen()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int st_to_int(char * st, int base);
void int_to_st(int n, char * buffer, int base);
void reverse_string(char * buffer);
int main(void) {
char input[] = "0D76";
int n = st_to_int("0D76", 16);
printf("Hex string '%s' converted to an int is %d.\n", input, n);
char buffer[100];
int_to_st(n, buffer, 10);
printf("%d converted to a decimal string is '%s'.\n", n, buffer);
int_to_st(n, buffer, 16);
printf("%d converted to a hex string is '%s'.\n", n, buffer);
return EXIT_SUCCESS;
}
int st_to_int(char * st, int base) {
static const char digits[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
int result = 0;
while ( *st ) {
result *= base;
for ( int i = 0; i < (int) sizeof(digits); ++i ) {
if ( digits[i] == tolower(*st) ) {
result += i;
break;
}
}
++st;
}
return result;
}
void int_to_st(int n, char * buffer, int base) {
static const char digits[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
int i = 0;
while ( n > 0 ) {
int next_digit = n % base;
n = n / base;
buffer[i++] = digits[next_digit];
}
buffer[i] = 0;
reverse_string(buffer);
}
void reverse_string(char * buffer) {
int buflen = strlen(buffer) + 1;
char revbuf[buflen];
int i;
for ( i = 0; i < buflen - 1; ++i ) {
revbuf[i] = buffer[buflen - 2 - i];
}
revbuf[i] = 0;
for ( i = 0; i < buflen; ++i ) {
buffer[i] = revbuf[i];
}
}
这给出了输出:
paul@local:~/src/c/scratch/strconv$ ./strconv
Hex string '0D76' converted to an int is 3446.
3446 converted to a decimal string is '3446'.
3446 converted to a hex string is 'd76'.
paul@local:~/src/c/scratch/strconv$
此代码不检查缓冲区溢出或无效输入(例如非字母数字输入),留作练习。同样,它不处理负数或 0。很容易修改,但您想避免“复杂/冗长”。