Convert Decimal To Hexa-Decimal including negative numbers
Given a number N in decimal format, the task is to convert it to the hexadecimal representation of N as a string. Negative numbers are stored in 2’s complement form.
Examples:
Input: N = 134
Output: 86
Explanation:
134 = 00000000000000000000000010001000 in 32 bit representation. Grouping in four-size chunks and converting each chunk to equivalent hexadecimal yields 88. Also, we can see 8*16 + 6 = 134. We will also get the same result by remainder technique discussed in other post.Input: N = -1
Output: ffffffff
Approach: The idea is to store negative numbers in a bigger size to trick the compiler to read it as positive instead of negative and then use the normal remainder technique. Store num in a u_int, size of u_it is greater, it will be positive since MSB is 0.
For Java there is no unsigned int data type. So in case of java, convert number to long and make the 32 higher bits as all zeroes. Idea remains the same as above.
num = (long)Math.pow(2, 32) + num ;
Below is the implementation of the above approach:
C++
// C++ program to convert decimal // to hexadecimal covering negative numbers #include <bits/stdc++.h> using namespace std; // Function to convert decimal no. // to hexadecimal number string Hex( int num) { // map for decimal to hexa, 0-9 are // straightforward, alphabets a-f used // for 10 to 15. map< int , char > m; char digit = '0' ; char c = 'a' ; for ( int i = 0; i <= 15; i++) { if (i < 10) { m[i] = digit++; } else { m[i] = c++; } } // string to be returned string res = "" ; // check if num is 0 and directly return "0" if (!num) { return "0" ; } // if num>0, use normal technique as // discussed in other post if (num > 0) { while (num) { res = m[num % 16] + res; num /= 16; } } // if num<0, we need to use the elaborated // trick above, lets see this else { // store num in a u_int, size of u_it is greater, // it will be positive since msb is 0 u_int n = num; // use the same remainder technique. while (n) { res = m[n % 16] + res; n /= 16; } } return res; } // Driver Code int main() { int x = 134, y = -1, z = -234; cout << "Hexa representation for" << endl; cout << x << " is " << Hex(x) << endl; cout << y << " is " << Hex(y) << endl; cout << z << " is " << Hex(z) << endl; return 0; } |
Java
// Java program to convert decimal // to hexadecimal covering negative numbers import java.util.*; import java.util.HashMap; import java.util.Map; class GFG { // Function to convert decimal no. // to hexadecimal number static String Hex( int num) { // map for decimal to hexa, 0-9 are // straightforward, alphabets a-f used // for 10 to 15. HashMap<Integer, Character> m = new HashMap<Integer, Character>(); char digit = '0' ; char c = 'a' ; for ( int i = 0 ; i <= 15 ; i++) { if (i < 10 ) { m.put(i, digit); digit++; } else { m.put(i, c); c++; } } // string to be returned String res = "" ; // check if num is 0 and directly return "0" if (num == 0 ) { return "0" ; } // if num>0, use normal technique as // discussed in other post if (num > 0 ) { while (num != 0 ) { res = m.get(num % 16 ) + res; num /= 16 ; } } // if num<0, we need to use the elaborated // trick above, lets see this else { // store num in a u_int, size of u_it is greater, // it will be positive since msb is 0 long n = num; n = ( long )Math.pow( 2 , 32 ) + num ; // use the same remainder technique. while (n != 0 ) { res = m.get(n % 16 ) + res; n /= 16 ; } } return res; } // Driver Code public static void main(String []args) { int x = 134 , y = - 1 , z = - 234 ; System.out.println( "Hexa representation for" ); System.out.println(x + " is " + Hex(x)); System.out.println( y + " is " + Hex(y)); System.out.println( z + " is " + Hex(z)); } } // This code is contributed by chitranayal |
Python3
# Python3 program to convert decimal # to hexadecimal covering negative numbers # Function to convert decimal no. # to hexadecimal number def Hex (num) : # map for decimal to hexa, 0-9 are # straightforward, alphabets a-f used # for 10 to 15. m = dict .fromkeys( range ( 16 ), 0 ); digit = ord ( '0' ); c = ord ( 'a' ); for i in range ( 16 ) : if (i < 10 ) : m[i] = chr (digit); digit + = 1 ; else : m[i] = chr (c); c + = 1 # string to be returned res = ""; # check if num is 0 and directly return "0" if ( not num) : return "0" ; # if num>0, use normal technique as # discussed in other post if (num > 0 ) : while (num) : res = m[num % 16 ] + res; num / / = 16 ; # if num<0, we need to use the elaborated # trick above, lets see this else : # store num in a u_int, size of u_it is greater, # it will be positive since msb is 0 n = num + 2 * * 32 ; # use the same remainder technique. while (n) : res = m[n % 16 ] + res; n / / = 16 ; return res; # Driver Code if __name__ = = "__main__" : x = 134 ; y = - 1 ; z = - 234 ; print ( "Hexa representation for" ); print (x, "is" , Hex (x)); print (y, "is" , Hex (y)); print (z, "is" , Hex (z)); # This code is contributed by AnkitRai01 |
C#
// C# program to convert decimal // to hexadecimal covering negative numbers using System; using System.Collections.Generic; public class GFG { // Function to convert decimal no. // to hexadecimal number static string Hex( long num) { // map for decimal to hexa, 0-9 are // straightforward, alphabets a-f used // for 10 to 15. IDictionary< long , char > m = new Dictionary< long , char >(); char digit = '0' ; char c = 'a' ; for ( int i = 0; i <= 15; i++) { if (i < 10) { m[i] = digit; digit++; } else { m[i] = c; c++; } } // string to be returned string res = "" ; // check if num is 0 and directly return "0" if (num == 0) { return "0" ; } // if num>0, use normal technique as // discussed in other post if (num > 0) { while (num != 0) { res = m[num % 16] + res; num /= 16; } } // if num<0, we need to use the elaborated // trick above, lets see this else { // we shall convert num to a 32 bit number num = ( long )Math.Pow(2, 32) + num; long n = num; // use the same remainder technique. while (n != 0) { res = m[n % 16] + res; n /= 16; } } return res; } public static void Main( string [] args) { long x = 134, y = -1, z = -234; Console.WriteLine( "Hexa representation for" ); Console.WriteLine(x + " is " + Hex(x)); Console.WriteLine(y + " is " + Hex(y)); Console.WriteLine(z + " is " + Hex(z)); } } // this code is contributed by phasing17 |
Javascript
<script> // JavaScript program to convert decimal // to hexadecimal covering negative numbers // Function to convert decimal no. // to hexadecimal number function Hex(num) { // map for decimal to hexa, 0-9 are // straightforward, alphabets a-f used // for 10 to 15. let m = new Map(); let digit = '0' .charCodeAt(0); let c = 'a' .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++; } } // string to be returned let res = "" ; // check if num is 0 and directly return "0" if (num == 0) { return "0" ; } // if num>0, use normal technique as // discussed in other post if (num > 0) { while (num != 0) { res = m.get(num % 16) + res; num =Math.floor(num/ 16); } } // if num<0, we need to use the elaborated // trick above, lets see this else { // store num in a u_int, size of u_it is greater, // it will be positive since msb is 0 let n = num+Math.pow(2,32); // use the same remainder technique. while (n != 0) { res = m.get(n % 16) + res; n = Math.floor(n/16); } } return res; } // Driver Code let x = 134, y = -1, z = -234; document.write( "Hexa representation for<br>" ); document.write(x + " is " + Hex(x)+ "<br>" ); document.write( y + " is " + Hex(y)+ "<br>" ); document.write( z + " is " + Hex(z)+ "<br>" ); // This code is contributed by rag2127 </script> |
Hexa representation for 134 is 86 -1 is ffffffff -234 is ffffff16
Time Complexity: O(log16num)
Auxiliary Space: O(1)
Method: Using look up table method
The function decToHex takes an integer num as input and returns its hexadecimal representation as a string. It first initializes a lookup table hexLookupTable which maps integers from 0 to 15 to their corresponding hexadecimal characters.
If num is positive, it uses the same technique as discussed in the previous post to convert it to hexadecimal. If num is negative, it converts it to an unsigned 32-bit integer n using a static cast, and then uses the same technique to convert n to hexadecimal. Finally, it returns the resulting hexadecimal string.
C++
#include <iostream> #include <unordered_map> using namespace std; // Function to convert decimal no. to hexadecimal number string decToHex( int num) { // Lookup table for hexadecimal values unordered_map< int , char > hexLookupTable{ {0, '0' }, {1, '1' }, {2, '2' }, {3, '3' }, {4, '4' }, {5, '5' }, {6, '6' }, {7, '7' }, {8, '8' }, {9, '9' }, {10, 'A' }, {11, 'B' }, {12, 'C' }, {13, 'D' }, {14, 'E' }, {15, 'F' } }; string res = "" ; // check if num is 0 and directly return "0" if (num == 0) { return "0" ; } // if num>0, use normal technique as discussed in other post if (num > 0) { while (num) { res = hexLookupTable[num % 16] + res; num /= 16; } } // if num<0, we need to use the elaborated trick above else { // convert num to 32-bit unsigned integer uint32_t n = static_cast <uint32_t>(num); // use the same remainder technique while (n) { res = hexLookupTable[n % 16] + res; n /= 16; } } return res; } int main() { int x = 134, y = -1, z = -234; cout << "Hexa representation for" << endl; cout << x << " is " << decToHex(x) << endl; cout << y << " is " << decToHex(y) << endl; cout << z << " is " << decToHex(z) << endl; return 0; } |
Java
import java.util.HashMap; public class GFG { // Function to convert a decimal number to its // hexadecimal representation public static String decToHex( int num) { // Create a lookup table to map decimal digits to // their corresponding hexadecimal characters HashMap<Integer, Character> hexLookupTable = new HashMap<>(); hexLookupTable.put( 0 , '0' ); hexLookupTable.put( 1 , '1' ); hexLookupTable.put( 2 , '2' ); hexLookupTable.put( 3 , '3' ); hexLookupTable.put( 4 , '4' ); hexLookupTable.put( 5 , '5' ); hexLookupTable.put( 6 , '6' ); hexLookupTable.put( 7 , '7' ); hexLookupTable.put( 8 , '8' ); hexLookupTable.put( 9 , '9' ); hexLookupTable.put( 10 , 'A' ); hexLookupTable.put( 11 , 'B' ); hexLookupTable.put( 12 , 'C' ); hexLookupTable.put( 13 , 'D' ); hexLookupTable.put( 14 , 'E' ); hexLookupTable.put( 15 , 'F' ); StringBuilder res = new StringBuilder(); // Special cases if (num == 0 ) { return "0" ; } // If the number is positive, convert it to hexadecimal if (num > 0 ) { while (num > 0 ) { res.insert( 0 , hexLookupTable.get(num % 16 )); num /= 16 ; } } // If the number is negative, convert its two's complement // to hexadecimal else { // Convert the negative number to a 32-bit unsigned // integer long n = ( long ) num & 0xffffffffL; while (n > 0 ) { res.insert( 0 , hexLookupTable.get(( int ) (n % 16 ))); n /= 16 ; } } return res.toString(); } public static void main(String[] args) { int x = 134 , y = - 1 , z = - 234 ; System.out.println( "Hexadecimal representation for:" ); System.out.println(x + " is " + decToHex(x)); System.out.println(y + " is " + decToHex(y)); System.out.println(z + " is " + decToHex(z)); } } |
Python3
def dec_to_hex(num): # Lookup table for hexadecimal values hex_lookup_table = { 0 : '0' , 1 : '1' , 2 : '2' , 3 : '3' , 4 : '4' , 5 : '5' , 6 : '6' , 7 : '7' , 8 : '8' , 9 : '9' , 10 : 'A' , 11 : 'B' , 12 : 'C' , 13 : 'D' , 14 : 'E' , 15 : 'F' } res = "" # Check if num is 0 and directly return "0" if num = = 0 : return "0" # If num > 0, use normal technique if num > 0 : while num: res = hex_lookup_table[num % 16 ] + res num / / = 16 # If num < 0, use the same remainder technique else : # Convert num to 32-bit unsigned integer n = num & 0xFFFFFFFF while n: res = hex_lookup_table[n % 16 ] + res n / / = 16 return res x = 134 y = - 1 z = - 234 print ( "Hexa representation for" ) print (x, "is" , dec_to_hex(x)) print (y, "is" , dec_to_hex(y)) print (z, "is" , dec_to_hex(z)) |
C#
using System; using System.Collections.Generic; namespace DecimalToHexConversionExample { class Program { // Function to convert decimal number to hexadecimal number static string DecToHex( int num) { // Lookup table for hexadecimal values Dictionary< int , char > hexLookupTable = new Dictionary< int , char > { {0, '0' }, {1, '1' }, {2, '2' }, {3, '3' }, {4, '4' }, {5, '5' }, {6, '6' }, {7, '7' }, {8, '8' }, {9, '9' }, {10, 'A' }, {11, 'B' }, {12, 'C' }, {13, 'D' }, {14, 'E' }, {15, 'F' } }; string res = "" ; // Check if num is 0 and directly return "0" if (num == 0) { return "0" ; } // If num > 0, use normal technique as discussed in other post if (num > 0) { while (num > 0) { res = hexLookupTable[num % 16] + res; num /= 16; } } // If num < 0, we need to use the elaborated trick above else { // Convert num to 32-bit unsigned integer uint n = ( uint )Math.Abs(num); // Use the same remainder technique while (n > 0) { res = hexLookupTable[( int )(n % 16)] + res; n /= 16; } } return res; } // Main code to test the function static void Main( string [] args) { int x = 134, y = -1, z = -234; Console.WriteLine( "Hexa representation for" ); Console.WriteLine($ "{x} is {DecToHex(x)}" ); Console.WriteLine($ "{y} is {DecToHex(y)}" ); Console.WriteLine($ "{z} is {DecToHex(z)}" ); } } } |
Javascript
function decToHex(num) { // Lookup table for hexadecimal values const hexLookupTable = { 0: '0' , 1: '1' , 2: '2' , 3: '3' , 4: '4' , 5: '5' , 6: '6' , 7: '7' , 8: '8' , 9: '9' , 10: 'A' , 11: 'B' , 12: 'C' , 13: 'D' , 14: 'E' , 15: 'F' }; let res = "" ; // Check if num is 0 and directly return "0" if (num === 0) { return "0" ; } // If num > 0, use normal technique if (num > 0) { while (num > 0) { res = hexLookupTable[num % 16] + res; num = Math.floor(num / 16); } } // If num < 0, use the elaborated trick else { // Convert num to 32-bit unsigned integer let n = Math.abs(num); // Use the same remainder technique while (n > 0) { res = hexLookupTable[n % 16] + res; n = Math.floor(n / 16); } } return res; } // Test the function const x = 134, y = -1, z = -234; console.log( "Hexadecimal representation for:" ); console.log(`${x} is ${decToHex(x)}`); console.log(`${y} is ${decToHex(y)}`); console.log(`${z} is ${decToHex(z)}`); |
Hexa representation for 134 is 86 -1 is FFFFFFFF -234 is FFFFFF16
Time complexity: The time complexity of this function is O(log(n)), where num is the magnitude of the input integer.
Auxiliary space: The auxiliary space used by this function is O(log(n)), where num is the magnitude of the input integer.