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
function Hex ( num ) { let m = new Map ( ) ; let digit = ' ' . charCodeAt ( 0 ) ; let c = ' ' . charCodeAt ( 0 ) ; for ( let i = 0 ; i <= 15 ; i ++ ) { if ( i < 10 ) { m . set ( i , String . fromCharCode ( digit ) ) ; digit ++ ; } else { m . set ( i , String . fromCharCode ( c ) ) ; c ++ ; } } let res = " " ; if ( num == 0 ) { return " " ; } if ( num > 0 ) { while ( num != 0 ) { res = m . get ( num % 16 ) + res ; num = Math . floor ( num / 16 ) ; } } else { let n = num + Math . pow ( 2 , 32 ) ; while ( n != 0 ) { res = m . get ( n % 16 ) + res ; n = Math . floor ( n / 16 ) ; } } return res ; } let x = 134 , y = - 1 , z = - 234 ; document . write ( " " ) ; document . write ( x + " " + Hex ( x ) + " " ) ; document . write ( y + " " + Hex ( y ) + " " ) ; document . write ( z + " " + Hex ( z ) + " " ) ;