Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Convert integer to hex integer

Tags:

java

integer

hex

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)

like image 554
user1215143 Avatar asked Feb 17 '12 01:02

user1215143


People also ask

Which method converts an int value into its equivalent hexadecimal?

An integer can be converted to a hexadecimal by using the string. ToString() extension method.

How do you convert int to hex in python?

hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.


2 Answers

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

like image 55
Ajith Avatar answered Sep 19 '22 17:09

Ajith


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.

like image 34
João Silva Avatar answered Sep 18 '22 17:09

João Silva