MD *_*LAM 4 c hex decimal number-formatting
为什么我们使用+ 55将十进制转换为十六进制数.在这段代码中,我们使用+48将整数转换为字符.当temp <10.但是当temp> = 10时,我们使用+55.+55是什么意思?
#include<stdio.h>
int main(){
long int decimalNumber,remainder,quotient;
int i=1,j,temp;
char hexadecimalNumber[100];
printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);
quotient = decimalNumber;
while(quotient!=0){
temp = quotient % 16;
//To convert integer into character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexadecimalNumber[i++]= temp;
quotient = quotient / 16;
}
printf("Equivalent hexadecimal value of decimal number %d: ",decimalNumber);
for(j = i -1 ;j> 0;j--)
printf("%c",hexadecimalNumber[j]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在ASCII环境中,55等于'A' - 10.这意味着添加55与减去10和添加相同'A'.
在ASCII中,'A'through 的值'Z'是相邻的和顺序的,因此这将映射10到'A'11 'B',依此类推.
对于temp小于10的值,相应的ASCII代码为48 + temp:
0 => 48 + 0 => '0'
1 => 48 + 1 => '1'
2 => 48 + 2 => '2'
3 => 48 + 3 => '3'
4 => 48 + 4 => '4'
5 => 48 + 5 => '5'
6 => 48 + 6 => '6'
7 => 48 + 7 => '7'
8 => 48 + 8 => '8'
9 => 48 + 9 => '9'
Run Code Online (Sandbox Code Playgroud)
对于10或更大的值,相应的字母是55 + temp:
10 => 55 + 10 => 'A'
11 => 55 + 11 => 'B'
12 => 55 + 12 => 'C'
13 => 55 + 13 => 'D'
14 => 55 + 14 => 'E'
15 => 55 + 15 => 'F'
Run Code Online (Sandbox Code Playgroud)