Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 13, 2004

Convert Your Data to Decimal/Integer Value

Generally speaking, the data you're being asked to process most likely has not been input in the format you need. It comes in hexadecimal, octal, or even in binary formats.

Converting this data into decimal/integer format can be tedious. Fortunately, the Java API provides a method that performs this conversion without any overhead for the developer.

The method takes two arguments. The first argument is the string value that needs to be converted to integer format. The second argument establishes the type of the argument—whether it is in hexadecimal, octal, or binary format. In the following code, the syntax is Integer.parseInt(stringValue,radixValue);. stringValue is the value to be converted and radixValue is the value for hexadecimal, octal, or binary as 16, 8, or 2 respectively:

 
String hexVal = "A"; //Hexadecimal
String octVal = "81"; //Octal
String binVal = "1101"; //Binary
 
System.out.println("Hex to Decimal. Hex = "+ hexVal + ", 
Decimal = "+Integer.parseInt(hexVal,16);
System.out.println("Octal to Decimal. Hex = "+ octVal + ", 
Decimal = "+Integer.parseInt(octVal,8);
System.out.println("Binary to Decimal. Hex = "+ binVal + ", 
Decimal = "+Integer.parseInt(binVal,2);
The result is the conversion from the respective formats to decimal value.
Sridhar MS
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap