Converting 32-bit unsigned integer (big endian) to long and back

后端 未结 3 2055
北恋
北恋 2020-12-16 03:57

I have a byte[4] which contains a 32-bit unsigned integer (in big endian order) and I need to convert it to long (as int can\'t hold an unsigned number).

Also, how d

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 04:47

    Sounds like a work for the ByteBuffer.

    Somewhat like

    public static void main(String[] args) {
        byte[] payload = toArray(-1991249);
        int number = fromArray(payload);
        System.out.println(number);
    }
    
    public static  int fromArray(byte[] payload){
        ByteBuffer buffer = ByteBuffer.wrap(payload);
        buffer.order(ByteOrder.BIG_ENDIAN);
        return buffer.getInt();
    }
    
    public static byte[] toArray(int value){
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.putInt(value);
        buffer.flip();
        return buffer.array();
    }
    

提交回复
热议问题