Convert decimal to hexadecimal

Why we use + 55 to convert a decimal number to a hexadecimal number. in this code we use +48 to convert an integer to a character. when temp <10. But when temp> = 10, we use +55. What does this mean +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; } 
+4
source share
3 answers

In ASCII 55, it is 'A' - 10 . This means that adding 55 is the same as subtracting 10 and adding 'A' .

In ASCII, values ​​from 'A' to 'Z' are contiguous and sequential, so this will display from 10 to 'A' , from 11 to 'B' and so on.

+8
source

For temp values ​​less than 10, the corresponding 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 ​​of 10 or more, the corresponding 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' 
+5
source

Due to the ASCII character encoding in C. When the remainder ( temp ) is less than ten, the hexadecimal digit is also in the range from 0 to 9. The characters "0" - "9" are in the ASCII range from 48 to 57.

When the remainder is greater than 10 (and always less than 15, due to the operation of the remainder % ), the hexadecimal digit is in the range from A to F, which in ASCII is in the range from 65 to 70. Thus, temp + 55 is a number from 65 to 70 and thus gives a character in the range of 'A' to 'F'.

The most commonly used string is char[] digits = "0123456789ABCDEF"; and use the remainder as an index on this line. The method in your question (maybe) also works.

+4
source

Source: https://habr.com/ru/post/1484522/


All Articles