2

Can you please answer this doubt related to java..

I would like to store MAX_VALUE of unsigned long (i.e 2(pow)64 -1) a n 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 i.e ignoring the signed bit. Please suggest on how to do this. Thanks.

2
  • There is no sign bit in 2's complement binary representation. Commented Nov 19, 2017 at 14:40
  • 1
    "I would like to store MAX_VALUE of unsigned long (i.e 2(pow)64 -1) a n byte array" Ok: byte[] b = {-1, -1, -1, -1, -1, -1, -1, -1} Commented Nov 19, 2017 at 14:46

1 Answer 1

6

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));
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Using a ByteBuffer is probably better than using DataInputStream /DataOutputStream. Less overhead and you have option of choosing big- vs little-endian mode.
Also, "FFFFFFFF" is only MAX_UNSIGNED_INT. You need double that, i.e. "FFFFFFFFFFFFFFFF" for MAX_UNSIGNED_LONG.
@Andreas absolutely. Fixed now. Not very used to ByteBuffer, so I hope this is the best way of using it.
No need for LongBuffer. Just use putLong and getLong on ByteBuffer, and you can chain it all: return ByteBuffer.allocate(8).putLong(value).array(); and return ByteBuffer.wrap(array).getLong();
And if you want Little Endian, you can add that to the chain, e.g. return ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getLong();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.