james
james

Reputation: 221

How to store a big integer valueintoan ArrayList of Byte

How can i store a int value=100,000 into a ArrayList<Byte>. I can't type cast because the value would change .

Is there any mechanism by which i can allocate 4 bytes in Arraylist and store the integer.

Or is it possible to with a byte[] array?

Upvotes: 0

Views: 1183

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

Or is it possible to with a byte[] array?

Yes, BigInteger have a method toByteArray()

byte[] resultBArray= yourBigInteger.toByteArray();

Even then you cannot store in ArrayList<Byte>, Since Byte[] is not Byte

But that seems not quite good for me, You can take a individual List with Byte[] or direct List<BigInteger>

BigInteger yourBigInteger = new BigInteger(String.valueOf(100000));
byte[] resultBArray= yourBigInteger.toByteArray();

to get it back

 int i=    new BigInteger(bytes).intValue();

Upvotes: 4

user2997937
user2997937

Reputation: 71

Just do

 byte[] byteArray = new BigInteger("100000").toByteArray();
 List<Byte> bytes = new ArrayList<>();
    for(byte b : byteArray)
        bytes.add(b);

Upvotes: 0

Masudul
Masudul

Reputation: 21961

Try:

BigInteger value=new BigInteger("100000");
List<byte[]> list=new   ArrayList<>();
list.add(value.toByteArray());//Put BigInteger as byte[]

BigInteger returnValue= new BigInteger(list.get(0));// Return value from list
System.out.println(returnValue);

Upvotes: 0

Related Questions