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)
The easiest way is to use Integer.toHexString(int)
Convert 20 to 32 (which is 0x20). Do that, and you've addressed this (highly unusual) question. The input is an integer. The output is a different integer. HOWEVER, THIS answer IS the highest voted one. Because it is what everyone (except the question-asker) wants!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.
20, it converts that to string "20", then treats that string as if it were a hexadecimal value, equivalent to 0x20, and produces the corresponding internal integer value. Internally (in all current mainstream cpus) that value is in binary: 0000 0000 0010 0000. Any representation occurs when you choose to display it. At that time, you can choose to see it in decimal: 32, as the question mentions, or you can see it in hex: "20" , by specifying an appropriate display format.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.
String hex = String.format("%02X", int); for fixed length (two characters with eventual leading zeros).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: 0*16^0+2*16^1=32 and 4*16^0+5*16^1=84
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)));
}
Integer, vs. representing that value in either decimal or hexadecimal.