0

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?

james
  • 221
  • 5
  • 16

3 Answers3

4

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();
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I have a int value=100000; how can i store this one?Its not a Integer Object. – james Nov 17 '13 at 06:47
  • You can create an Wrapper object from primitive. Like http://stackoverflow.com/questions/3878192/converting-from-integer-to-biginteger – Suresh Atta Nov 17 '13 at 06:52
  • Why do i have to convert it to bigInteger? can i jus have it as Integer? – james Nov 17 '13 at 06:56
  • @james Then that is cherry on cake :) `Integer intObj = new Integer(100000);` – Suresh Atta Nov 17 '13 at 06:58
  • This is not working , can you tell me what wrong here? int value=100000;Integer intObj = new Integer(value); byte[] resultBArray= intObj.toByteArray();//error here – james Nov 17 '13 at 07:46
  • @james Why you are converting it in to Integer ? Integer doesn't have a facility to give bytes.Use Big Integer. – Suresh Atta Nov 17 '13 at 07:54
  • Ok , How to get back the int value from byte[] now?I used for(int j=0;j – james Nov 17 '13 at 08:05
0

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);
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

Just do

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