Thursday, March 31, 2011

Conversion from integer to hexadecimal and vice-versa

You can convert a hexadecimal to integer using two different methods as shown below:
int i = Integer.valueOf("B8DA3"16).intValue();

   or

int i = Integer.parseInt("B8DA3"16);  


You can convert a decimal to binary using three different methods as shown below:

int i = 42;
String hexstr = Integer.toString(i, 16);

or

String hexstr = Integer.toHexString(i);

or (with leading zeroes and uppercase)

public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}

No comments:

Post a Comment

Chitika