Java Convert integer to hex integer

JavaIntegerHex

Java Problem Overview


I'm trying to convert a number from an integer into an another integer which, if printed in hex, would look the same as the original integer.

For example:

Convert 20 to 32 (which is 0x20)

Convert 54 to 84 (which is 0x54)

Java Solutions


Solution 1 - Java

The easiest way is to use Integer.toHexString(int)

Solution 2 - Java

public static int convert(int n) {
  return Integer.valueOf(String.valueOf(n), 16);
}

public static void main(String[] args) {
  System.out.println(convert(20));  // 32
  System.out.println(convert(54));  // 84
}

That is, treat the original number as if it was in hexadecimal, and then convert to decimal.

Solution 3 - Java

Another way to convert int to hex.

String hex = String.format("%X", int);

You can change capital X to x for lowercase.

Example:

String.format("%X", 31) results 1F.

String.format("%X", 32) results 20.

Solution 4 - Java

int orig = 20;
int res = Integer.parseInt(""+orig, 16);

Solution 5 - Java

You could try something like this (the way you would do it on paper):

public static int solve(int x){
    int y=0;
    int i=0;

    while (x>0){
        y+=(x%10)*Math.pow(16,i);
        x/=10;
        i++;
    }
    return y;
}

public static void main(String args[]){
    System.out.println(solve(20));
    System.out.println(solve(54));
}

For the examples you have given this would calculate: 016^0+216^1=32 and 416^0+516^1=84

Solution 6 - Java

String input = "20";
int output = Integer.parseInt(input, 16); // 32

Solution 7 - Java

The following is optimized iff you only want to print the hexa representation of a positive integer.

It should be blazing fast as it uses only bit manipulation, the utf-8 values of ASCII chars and recursion to avoid reversing a StringBuilder at the end.

public static void hexa(int num) {
    int m = 0;
    if( (m = num >>> 4) != 0 ) {
    	hexa( m );
    }
    System.out.print((char)((m=num & 0x0F)+(m<10 ? 48 : 55)));
}

Solution 8 - Java

Simply do this:

public static int specialNum(num){

    return Integer.parseInt( Integer.toString(num) ,16)
}

It should convert any special decimal integer to its hexadecimal counterpart.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1215143View Question on Stackoverflow
Solution 1 - JavaAjithView Answer on Stackoverflow
Solution 2 - JavaJoão SilvaView Answer on Stackoverflow
Solution 3 - JavaWitView Answer on Stackoverflow
Solution 4 - JavaSergey KalinichenkoView Answer on Stackoverflow
Solution 5 - JavappalasekView Answer on Stackoverflow
Solution 6 - JavadriangleView Answer on Stackoverflow
Solution 7 - JavaSnicolasView Answer on Stackoverflow
Solution 8 - Javaed9w2in6View Answer on Stackoverflow