BigInteger toByteArray() Method in Java
The java.math.BigInteger.toByteArray() method returns a array of byte containing the two’s-complement representation of this BigInteger. The most significant byte of byte array is present in the zeroth element. The returning array from this method contain sing bit and conntain the minimum number of bytes required to represent this BigInteger. The sign bit position is (ceil((this.bitLength() + 1)/8)).
Syntax:
public byte[] toByteArray()
Parameters: This method does not accepts any parameters.
Return Value: This method returns a byte array containing the two’s-complement representation of this BigInteger.
Below programs illustrate toByteArray() method of BigInteger class:
Example 1:
// Java program to demonstrate toByteArray() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger bigInt = BigInteger.valueOf(10); // create a byte array byte b1[]; b1 = bigInt.toByteArray(); // print result System.out.print("ByteArray of BigInteger " + bigInt + " is"); for (int i = 0; i < b1.length; i++) { System.out.format(" " + "0x%02X", b1[i]); } } } |
ByteArray of BigInteger 10 is 0x0A
Example 2:
// Java program to demonstrate toByteArray() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // create byte array byte b[] = { 0x1, 0x2, 0x1 }; // Creating BigInteger object using byte Array BigInteger bigInt = new BigInteger(b); // apply toByteArray() on BigInteger byte b1[] = bigInt.toByteArray(); // print result System.out.print("ByteArray of BigInteger " + bigInt + " is"); for (int i = 0; i < b1.length; i++) { System.out.format(" " + "0x%02X", b1[i]); } } } |
ByteArray of BigInteger 66049 is 0x01 0x02 0x01
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toByteArray()
Recommended Posts:
- BitSet toByteArray() Method in Java with Examples
- BigInteger xor() Method in Java
- BigInteger or() method in Java
- BigInteger mod() Method in Java
- BigInteger pow() Method in Java
- BigInteger abs() Method in Java
- BigInteger not() Method in Java
- BigInteger and() Method in Java
- BigInteger intValue() Method in Java
- BigInteger longValue() Method in Java
- BigInteger equals() Method in Java
- BigInteger compareTo() Method in Java
- BigInteger hashCode() Method in Java
- BigInteger setBit() Method in Java
- BigInteger floatValue() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



