0

I am working with large 32 bit numbers. I need to convert these numbers to byte format and write them to an array of bytes. For example, the number 434729217 will be stored in a byte array as [25,-23,113,1]. But also among large 32 bit numbers there can be zeros, and they will already be stored as [0], but I need everything to be fixed and they are stored as [0,0,0,0]. How can this be implemented?

I tried like this, but the numbers are still not written the way I would like

byte[] byteArray = new byte[4];
List<byte[]> byteList = new ArrayList<>();


byteArray = encrypt.toByteArray(); //encrypt is bigint 32 bit number
byteList.add(byteArray)

This is how bytes are stored

enter image description here

  • 1
    I don't understand your question. If you store the int value 0 as its bytes, it's going to be [0,0,0,0]. – knittl Nov 02 '22 at 06:56
  • 1
    Does this answer your question? [Convert integer into byte array (Java)](https://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java) – knittl Nov 02 '22 at 06:57
  • I added a photo of how bytes are stored. And I don't have an int, but a BigInteger – Rume Diablo Nov 02 '22 at 06:59
  • If it is 32 bits only: convert to `int`, use the existing solutions. If it's not: check array length and copy to array of the required size. – knittl Nov 02 '22 at 07:04
  • Also: what do you want to do when your `BigInteger` can't be represented as a 32 bit `int`? – knittl Nov 04 '22 at 17:34

1 Answers1

0
public static void main(String[] args){
    List<byte[]> byteList = new ArrayList<>();
    BigInteger encrypt = new BigInteger("434729217");
    int value = encrypt.intValue();
    byte[] byteArray = toHH(value);
    byteList.add(byteArray)
}

public static byte[] toHH(int n) {  
  byte[] b = new byte[4];  
  b[3] = (byte) (n & 0xff);  
  b[2] = (byte) (n >> 8 & 0xff);  
  b[1] = (byte) (n >> 16 & 0xff);  
  b[0] = (byte) (n >> 24 & 0xff);  
  return b;  
}
lhDream
  • 1
  • 2