Search code examples
javabyteuint32

Java uint32 (stored as long) to 4 byte array


I'm writing to a storage format that has uint32, with a max allowed value of "4294967295".

Integer in Java is, of course, just under half that at "2147483647". So internally, I have to use either Long or Guava's UnsignedInteger.

To write to this format, the byte array length needs to be 4, which fits Integer just fine, but converting Long to a byte array requires an array of length 8.

How can I convert a Long or UnsignedInteger representing a max value of "4294967295" as a 4 byte array?


Solution

  • Simply convert it to an 8 byte array and then take only the last 4 bytes:

     public static byte[] fromUnsignedInt(long value)
     {
         byte[] bytes = new byte[8];
         ByteBuffer.wrap(bytes).putLong(value);
    
         return Arrays.copyOfRange(bytes, 4, 8);
     }
    

    To reverse this you can use the following method:

     public static long toUnsignedInt(byte[] bytes)
     {
         ByteBuffer buffer = ByteBuffer.allocate(8).put(new byte[]{0, 0, 0, 0}).put(bytes);
         buffer.position(0);
    
         return buffer.getLong();
     }
    

    Note that this method CAN take a negative long or a long that exceed the range of an unsigned int and won't throw a exception in such a case!