2013-06-04 235 views
4

为什么我们使用+55将十进制转换为十六进制数。在这段代码中,我们使用+48将整数转换为字符。当临时< 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; 
} 
+0

http://www.asciitable.com/ –

回答

8

在ASCII环境中,55等于'A' - 10。这意味着添加55与减去10并添加'A'相同。

在ASCII中,'A''Z'的值是相邻的和顺序的,所以这将映射10到'A',11到'B'等等。

5

对于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' 

对于值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' 
+0

感谢兄弟@john –

4

由于的ASCII对C中字符的编码。当余数(temp)小于10时,十六进制数字也在0到9的范围内。字符'0'到'9'在48到57的ASCII范围内。

当余数大于10(并且总是小于15,由于余数操作%),十六进制数字为范围A到F,ASCII中的范围在65到70之间。因此,temp + 55是一个65到70之间的数字,因此给出的范围为'A'到'F'。

使用字符串char[] digits = "ABCDEF";更常见,并将余数用作此字符串中的索引。你的问题中的方法(可能)也适用。

+0

感谢兄弟@kninnug –

相关问题