简体   繁体   中英

converting byte[] array to unsigned Long java

Can you please answer this doubt related to java..

I would like to store MAX_VALUE of unsigned long (ie 2(pow)64 -1) an byte array, and then read byte[] array to get back this MAX_VALUE . As all data types are signed, so would like to know how to store 0xFF (each byte) value in each index of byte[] array ie ignoring the signed bit. Please suggest on how to do this. Thanks.

Something like this?

public class Utils {
    static byte[] longToByteArray(long value) {
        return ByteBuffer.allocate(8).putLong(value).array();
    }

    static long byteArrayToLong(byte[] array) {
        return ByteBuffer.wrap(array).getLong();
    }

    public static void main(String[] args) {
        long maxValue = Long.parseUnsignedLong("FFFFFFFFFFFFFFFF", 16);
        byte[] b = longToByteArray(maxValue);
        System.out.println("b = " + Arrays.toString(b));

        long value = byteArrayToLong(b);
        System.out.println("value = " + value);
        System.out.println("hex value = " + Long.toUnsignedString(value, 16));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM