Convert Decimal To Hexa | Function to convert decimal no . to hexadecimal number ; map for decimal to hexa , 0 - 9 are straightforward , alphabets a - f used for 10 to 15. ; string to be returned ; check if num is 0 and directly return "0" ; if num > 0 , use normal technique as discussed in other post ; if num < 0 , we need to use the elaborated trick above , lets see this ; store num in a u_int , size of u_it is greater , it will be positive since msb is 0 ; use the same remainder technique . ; Driver Code
def Hex ( num ) : NEW_LINE INDENT m = dict . fromkeys ( range ( 16 ) , 0 ) ; NEW_LINE digit = ord ( '0' ) ; NEW_LINE c = ord ( ' a ' ) ; NEW_LINE for i in range ( 16 ) : NEW_LINE INDENT if ( i < 10 ) : NEW_LINE INDENT m [ i ] = chr ( digit ) ; NEW_LINE digit += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT m [ i ] = chr ( c ) ; NEW_LINE c += 1 NEW_LINE DEDENT DEDENT res = " " ; NEW_LINE if ( not num ) : NEW_LINE INDENT return "0" ; NEW_LINE DEDENT if ( num > 0 ) : NEW_LINE INDENT while ( num ) : NEW_LINE INDENT res = m [ num % 16 ] + res ; NEW_LINE num //= 16 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT n = num + 2 ** 32 ; NEW_LINE while ( n ) : NEW_LINE INDENT res = m [ n % 16 ] + res ; NEW_LINE n //= 16 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 134 ; y = - 1 ; z = - 234 ; NEW_LINE print ( " Hexa ▁ representation ▁ for " ) ; NEW_LINE print ( x , " is " , Hex ( x ) ) ; NEW_LINE print ( y , " is " , Hex ( y ) ) ; NEW_LINE print ( z , " is " , Hex ( z ) ) ; NEW_LINE DEDENT