How do I convert BigInteger into another radix number?

In this example you’ll see how we can convert a java.math.BigInteger number into another radix such as binary, octal and hexadecimal.

package org.kodejava.example.math;

import java.math.BigInteger;

public class BigIntegerConversion {
    public static void main(String[] args) {
        BigInteger number = new BigInteger("2017");

        System.out.println("Number      = " + number);
        System.out.println("Binary      = " + number.toString(2));
        System.out.println("Octal       = " + number.toString(8));
        System.out.println("Hexadecimal = " + number.toString(16));

        number = new BigInteger("FF", 16);
        System.out.println("Number      = " + number);
        System.out.println("Number      = " + number.toString(16));
    }
}

The result of our examples:

Number      = 2017
Binary      = 11111100001
Octal       = 3741
Hexadecimal = 7e1
Number      = 255
Number      = ff

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.