Perform binary, octal, hexadecimal, and decimal conversion in Java
Convert decimal to hexadecimal:
Integer. tohexstring (int I)
Decimal to octal
Integer. tooctalstring (int I)
Convert decimal to binary
Integer. tobinarystring (int I)
Hexadecimal to decimal
Integer. valueof ("ffff", 16). tostring ()
Octal to decimal
Integer. valueof ("876", 8). tostring ()
Convert binary to decimal
Integer. valueof ("0101", 2). tostring ()
The Java. Lang. Integer class can be directly converted from 2, 8, and 16 to 10.
Integer. parseint (string S, int Radix)
Use the base number specified by the second parameter to resolve the string parameter to a signed integer.
Examples
Parseint ("0", 10) returns 0
Parseint ("473", 10) returns 473
Parseint ("-0", 10) returns 0
Parseint ("-FF", 16) returns-255
Parseint ("1100110", 2) returns 102
Parseint ("2147483647", 10) returns 2147483647
Parseint ("-2147483648", 10) returns-2147483648
Parseint ("2147483648", 10) throws a numberformatexception
Parseint ("99", 8) throws a numberformatexception
Parseint ("Kona", 10) throws a numberformatexception
Parseint ("Kona", 27) returns 411787.
How to Write (2, 8, 16) in hexadecimal conversion without Algorithms
Integer. tobinarystring
Integer. tooctalstring
Integer. tohexstring
Example 1
Java code
- Public class test {
- Public static void main (string ARGs []) {
- Int I = 100;
- String binstr = integer. tobinarystring (I );
- String otcstr = integer. tooctalstring (I );
- String hexstr = integer. tohexstring (I );
- System. Out. println (binstr );
Example 2
Java code
- Public class teststringformat {
- Public static void main (string [] ARGs ){
- If (ARGs. Length = 0 ){
- System. Out. println ("Usage: Java teststringformat <a number> ");
- System. Exit (0 );
- }
- Integer factor = integer. valueof (ARGs [0]);
- String S;
- S = string. Format ("% d", factor );
- System. Out. println (s );
- S = string. Format ("% x", factor );
- System. Out. println (s );
- S = string. Format ("% O", factor );
- System. Out. println (s );
- }
- }