NoeL
NoeL

Reputation: 67

How Does JVM Store Data to ByteBuffer?

I just learned about Java's ByteBuffer, I am a little confused with how JVM storing multiple data types into a ByteBuffer. This is the codes:

public static void main(String[] args) {
    ByteBuffer BF1 = ByteBuffer.allocate(30);
    BF1.putChar('A');
    BF1.putChar('B');
    BF1.putInt(129);
    BF1.putDouble(0.98);
    BF1.putFloat(8.9f);

    byte[] BA1 = new byte[BF1.position()];
    BF1.position(0);
    BF1.get(BA1, 0, BA1.length);
    System.out.print("BA1 =");
    for(byte a: BA1)
         System.out.print(" " + a);
}

/*output
  BA1 = 0 65 0 66 0 0 0 -127 63 -17 92 40 -11 -62 -113 92 65 14 102 102 **/

I understand that JVM writes Char types as 2 bytes, int types as 4 bytes, double types as 8 bytes, and Float types as 4 bytes. So, the input values in ByteBuffer should be:

A = 0 65, B = 0 66, 192 = 0 0 0 -127, 0.98 = 63 -17 92 40 -11 -62 -113 92, 8.9f = 65 14 102 102

My questions:

How JVM convert int 129 to be 0 0 0 -127, why is it not written as 0 0 0 129? Then how JVM convert Float and Double types in ByteBuffer like result above?

Thank you very much in advance.

Upvotes: 0

Views: 370

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533870

The simplest approach is to read the code. For example to write/read a long it calls

static void putLongB(ByteBuffer bb, int bi, long x) {
bb._put(bi + 0, long7(x));
bb._put(bi + 1, long6(x));
bb._put(bi + 2, long5(x));
bb._put(bi + 3, long4(x));
bb._put(bi + 4, long3(x));
bb._put(bi + 5, long2(x));
bb._put(bi + 6, long1(x));
bb._put(bi + 7, long0(x));
}

and

static long getLongB(long a) {
return makeLong(_get(a + 0),
        _get(a + 1),
        _get(a + 2),
        _get(a + 3),
        _get(a + 4),
        _get(a + 5),
        _get(a + 6),
        _get(a + 7));
}

assuming you have the default Big Endian byte order.

If you use a direct ByteBuffer it uses the Unsafe class which is treated as an intrinsic and turned into a machine code instruction. i.e. the CPU does the work.

Upvotes: 2

Related Questions