使用 C 语言将十六进制小数转换为整数值
问题
如何使用 C 编程语言将十六进制值转换为整数值?
解释概念.
解决方案
十六进制值以 16 个符号 1 到 9 和 A 到 F 表示。此处,A 到 F 的十进制等值为 10 到 15。
示例
以下是使用函数将十六进制转换为整数的 C 程序 -
#include<stdio.h>
#include<string.h>
#include<math.h>
int hextodc(char *hex){
int y = 0;
int dec = 0;
int 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);// converting hexadecimal to integer value ++y;
}
return dec;
}
int main(){
char hex[100];
printf("Enter Hexadecimal: ");
scanf("%s", hex);
printf("
Decimal: %d", hextodc(hex));
return 0;
}输出
执行上述程序后,会产生以下结果 -
1. Enter Hexadecimal: A Decimal: 10 2. Enter Hexadecimal: A12 Decimal: 2578
解释
从右到左扫描十六进制的所有字符
让扫描到的字符为 A。
将 A 转换为适当的十进制形式并将其存储在 x 中。
dec = dec + x * 16y
y= y + 1。
返回十进制数。
我们也可以从左到右扫描十六进制值,但是,我们必须将 y 初始化为 y = N – 1,并在每次迭代时将 y 减 1。N 是十六进制的长度。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP