Java convert BigInteger to byte

Tags: BigInteger BigInteger byteValueExact BigInteger byteValue byte

In this Java core tutorial we learn how to use the java.math.BigInteger.byteValueExact() and java.math.BigInteger.byteValue() method to convert a BigInteger object into a byte value.

How to convert BigInteger object to byte value

To convert a BigInteger value into byte value we can use the method java.math.BigInteger.byteValueExact(). This method also checks the value of BigInteger if it is out of range of byte then an ArithmeticException is thrown.

ConvertBigIntegerToByteExample1.java

import java.math.BigInteger;

public class ConvertBigIntegerToByteExample1 {
    public static void main(String... args) {
        BigInteger value = new BigInteger("123");

        byte byteValue = value.byteValueExact();

        System.out.println("BigInteger value: " + value);
        System.out.println("byte value: " + byteValue);
    }
}
The output is:
BigInteger value: 123
byte value: 123

We also can use the java.math.BigInteger.byteValue() method which casts the BigInteger value to byte.

ConvertBigIntegerToByteExample2.java

import java.math.BigInteger;

public class ConvertBigIntegerToByteExample2 {
    public static void main(String... args) {
        BigInteger value = new BigInteger("123");

        byte byteValue = value.byteValue();

        System.out.println("BigInteger value: " + value);
        System.out.println("byte value: " + byteValue);
    }
}
The output is:
BigInteger value: 123
byte value: 123

Happy Coding 😊