โจทย์
แปลงค่า Hexadecimal (ฐาน 16: 0-9, A-F) เป็น Integer (ฐาน 10)
โปรแกรม
#include <stdio.h>
#include <string.h>
#include <math.h>
int hextodec(char *hex) {
int y = 0, dec = 0, x, i;
for (i = strlen(hex) - 1; i >= 0; --i) {
if (hex[i] >= '0' && hex[i] <= '9')
x = hex[i] - '0';
else
x = hex[i] - 'A' + 10;
dec = dec + x * pow(16, y);
++y;
}
return dec;
}
int main() {
char hex[100];
printf("Enter Hexadecimal: ");
scanf("%s", hex);
printf("Decimal: %d\n", hextodec(hex));
return 0;
}
ผลลัพธ์
Enter Hexadecimal: A
Decimal: 10
Enter Hexadecimal: A12
Decimal: 2578
อธิบาย
- อ่าน Hex จากขวาไปซ้าย (LSB to MSB)
- แปลงตัวอักษรเป็นค่าตัวเลข (0-9, A=10..F=15)
- คูณด้วย 16^position รวมกัน