提供兩個函數:Read_DecNumber 將字串中的十進制數字轉為整數;Read_HexNumber 將字串中的十六進制數字 (0-9, A-F, a-f) 轉為整數。適用於解析配置檔、協議報文等場景。
#include <stdio.h>
typedef char TUINT8;
typedef int TUINT32;
TUINT32 Read_DecNumber(const TUINT8* str) {
TUINT32 value = 0;
if (!str) return 0;
while (*str >= '0' && *str <= '9') {
value = value * 10 + (*str - '0');
str++;
}
return value;
}
TUINT32 Read_HexNumber(const TUINT8* str) {
TUINT32 value = 0;
if (!str) return 0;
while (1) {
if (*str >= '0' && *str <= '9') {
value = value * 16 + (*str - '0');
} else if (*str >= 'A' && *str <= 'F') {
value = value * 16 + (*str - 'A') + 10;
} else if (*str >= 'a' && *str <= 'f') {
value = value * 16 + (*str - 'a') + 10;
} else {
break;
}
str++;
}
return value;
}
int main(void) {
int dec = Read_DecNumber("1000");
int hex = Read_HexNumber("A");
printf("十進制轉換: %d\n", dec); // 1000
printf("十六進制轉換: %d\n", hex); // 10
return 0;
}
輸出:
將字符串中的數字轉化為10進制數 :1000 將字符串中的16進制數轉化為10進制數 :10