1

Can we read a same sequence of bytes as different data-types in java? I was wondering if that is possible. The purpose is to demonstrate the representation of different data-types in memory, specifically Java.

Chris Dennett
  • 22,412
  • 8
  • 58
  • 84

2 Answers2

3

You can convert a double to and from long preserving its binary representation (rather than value) using the following methods: doubleToLongBits(), doubleToRawLongBits() and longBitsToDouble().

You can also use ByteBuffer like this:

import java.nio.ByteBuffer;

public class ByteShow {
  public static void showBytes(ByteBuffer bb) {
    byte[] bytes = bb.array();
    for (byte b : bytes) {
      System.out.format("0x02%x ", b);
    }
    System.out.println();
  }

  public static void main(String[] args) {
    showBytes(ByteBuffer.allocate(4).putInt(0x12345678));
    showBytes(ByteBuffer.allocate(8).putDouble(Math.PI))
    showBytes(ByteBuffer.allocate(2).putChar('@'));
  }
}

which outputs:

0x12 0x34 0x56 0x78 
0x40 0x09 0x21 0xfb 0x54 0x44 0x2d 0x18 
0x00 0x40 

See also this post.

Community
  • 1
  • 1
Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • This last part(main function) you added is exactly what I wanted, could not clearly mention in the question though... Thanks –  Nov 07 '11 at 21:04
0

You could use the Union type in Javolution ;)

Chris Dennett
  • 22,412
  • 8
  • 58
  • 84