本帖最后由 xieglt 于 2020-11-2 16:17 编辑
看看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//判定字符是否16进制数的宏
#define IS_HEX(c) ((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F'))
//将小写字符转变为大写字符
#define LCase2UCase(c) ((c>='a' && c<='z') ? (c-32) : c)
//将ascii字符转化为16进制数
#define ASCII2HEX(c) ((c-0X30)>9 ? (c-0X37) : (c-0X30))
//将16进制数转化为ascii字符
#define HEX2ASCII(c) ((c+0X30)>0X39 ? (c+0x37) : (c+0X30))
int main()
{
int m,n;
int i,max;
char Hex1[256] = {0};
char Hex2[256] = {0};
char Hex3[256] = {0};
char *p = Hex3+1;
char carry = 0;
char value = 0;
printf("hexadecimal number 1: ");
scanf("%s", Hex1);
printf("hexadecimal number 2: ");
scanf("%s", Hex2);
m = strlen(Hex1);
n = strlen(Hex2);
//判定输入Hex1是否16进制数
for(i=0 ; i<m ; i++)
{
if(!IS_HEX(Hex1[i]))
{
printf("%s is not a hexadecimal number!",Hex1);
return 0;
}
}
//判定输入Hex2是否16进制数
for(i=0 ; i<m ; i++)
{
if(!IS_HEX(Hex2[i]))
{
printf("%s is not a hexadecimal number!",Hex2);
return 0;
}
}
//将两个数对齐
if(m > n)
{
//Hex2位数少则对齐 Hex2
memcpy(Hex2+(m-n),Hex2,n);
//前面置字符'0'
memset(Hex2,0X30,m-n);
}
else if(m < n)
{
//Hex1位数少则对齐 Hex1
memcpy(Hex1+(n-m),Hex1,m);
//前面置字符'0'
memset(Hex1,0X30,n-m);
}
max = m > n ? m : n;
for(i=max-1 ; i >=0 ; i--)
{
//取得进位
value = carry;
//+数1
value += ASCII2HEX(LCase2UCase(Hex1[i]));
//+数2
value += ASCII2HEX(LCase2UCase(Hex2[i]));
//计算是否进位
carry = value/16;
//计算结果
value %= 16;
//转化为ASCII码保存
Hex3[i+1] = HEX2ASCII(value);
}
//如果还有进位,则保存进位
if(carry !=0)
{
Hex3[i+1] = HEX2ASCII(carry);
p = Hex3;
}
printf("%s\n",p);
return 0;
}
|