Convert Decimal To Hexa-Decimal including negative numbers - GeeksforGeeks

23 Mar, 2022
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: 86Explanation: 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 ides 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++
Java
Python3
Javascript
// C++ program to convert decimal// to hexadecimal covering negative numbers #include <bits/stdc++.h>using namespace std; // Function to convert decimal no.// to hexadecimal numberstring 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 Codeint 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 program to convert decimal// to hexadecimal covering negative numbersimport java.util.*;import java.util.HashMap;import java.util.Map; class GFG{ // Function to convert decimal no.// to hexadecimal numberstatic 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;        num =  (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 Codepublic 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 program to convert decimal# to hexadecimal covering negative numbers # Function to convert decimal no.# to hexadecimal numberdef 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 Codeif __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
<script> // JavaScript program to convert decimal// to hexadecimal covering negative numbers // Function to convert decimal no.// to hexadecimal numberfunction 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 Codelet 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(15)
ankthon
ukasp
rag2127
anirudhmuku
subham348
goofyblah
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Bits manipulation (Important tactics)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7