2013-06-04 233 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 –

相關問題