Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a decimal to a hexadecimal number

Why we use + 55 for converting decimal to hex num . in this code we use +48 to convert integer to character . when temp < 10 . But when temp > =10 we use +55 . what does it mean by +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;
}
like image 716
MD MAHBUB ALAM Avatar asked Dec 01 '22 03:12

MD MAHBUB ALAM


2 Answers

In an ASCII environment, 55 is equal to 'A' - 10. This means that adding 55 is the same as subtracting 10 and adding 'A'.

In ASCII, the values of 'A' through 'Z' are adjacent and sequential, so this will map 10 to 'A', 11 to 'B' and so on.

like image 143
caf Avatar answered Dec 05 '22 05:12

caf


For values of temp less than 10, the appropriate ASCII code is 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'

For values 10 or greater, the appropriate letter is 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'
like image 31
John Avatar answered Dec 05 '22 07:12

John