Java Convert Integer to Hexadecimal Integer

I am trying to convert a number from an integer to another integer which, if printed in hexadecimal, will look the same as the original integer.

For example:

Convert 20 to 32 (which equals 0x20)

Convert 54 to 84 (this is 0x54)

+52
java integer hex
Feb 17 2018-12-12T00:
source share
8 answers
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, process the original number as if it were in hexadecimal format, and then convert to decimal.

+39
Feb 17 '12 at 1:14
source share

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

+249
Nov 03 '12 at 16:50
source share

Another way to convert int to hex .

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

You can change the capital letter X to x .

Example:

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

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

+11
Jan 13 '16 at 9:10
source share
 int orig = 20; int res = Integer.parseInt(""+orig, 16); 
+7
Feb 17 '12 at 1:14
source share

You can 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)); } 

In the examples you indicated, will be calculated: 0 * 16 ^ 0 + 2 * 16 ^ 1 = 32 and 4 * 16 ^ 0 + 5 * 16 ^ 1 = 84

+5
Feb 17 '12 at 1:25
source share
 String input = "20"; int output = Integer.parseInt(input, 16); // 32 
+4
Feb 17 '12 at 1:14
source share

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

It should flash quickly since it only uses bit-manipulation, utf-8 values โ€‹โ€‹of ASCII characters and recursion to avoid changing 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))); } 
+1
Dec 11 '13 at 17:41
source share

Just do the following:

 public static int specialNum(num){ return Integer.parseInt( Integer.toString(num) ,16) } 

It must convert any special decimal integer to its hexadecimal copy.

0
May 22 '17 at 10:48 p.m.
source share



All Articles