Thursday, June 11, 2009

Hexadecimal, Octal, Binary conversion to Integer in Java

To convert a Hexadecimal value to an Integer format

Step 1:
First store the value as a string-
String s="DA";
Step 2:
Then the following step gives the integer value-
int a=Integer.parseInt(s,16);

This is sometimes necessary in Color conversions when color is represented in integer value and we know color in hexadecimal format.
Example:
If color is "0xd24ae5"
then the following steps will give us the integer value:-
Step 1:
String s="0xd24ae5";
Step 2:
String t=s.substring(2);
Step 3:
int a=Integer.parseInt(t,16);

To Convert Integer to Hexadecimal String

String hexvalue=Integer.toHexString(574);

Integer and Long class provide toBinaryString(), toHexString(), toOctalString() which are very valuable sometimes.
The steps are similar in converting Integer to Binary or Octal and vice versa.

For Converting Binary to Integer in Java

String s="11011010";
int a=Integer.parseInt(s,2);

This will give 218 as the answer.

Integer to Binary

String binaryval=Integer.toBinaryString(218);

This will give 11011010 as the string.

Similarly Octal to Integer and vice versa can be done.


Do tell me if you liked the above information!!

No comments:

Post a Comment

Write Your Comments..

Share this Page:-