Perform binary, octal, hexadecimal, and decimal conversion in Java

Source: Internet
Author: User
Tags binary to decimal decimal to binary

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 ()


Is there any way to directly convert 2, 8, and 16 to 10?

Java. Lang. Integer class

Parseint (string S, int Radix)

Use the base number specified by the second parameter to resolve the string parameter to a signed integer.

Examples from JDK:

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:

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:

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);  }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.