0

I have the following piece of code in C++

int magic;
stream.read(&magic, sizeof(magic));

Which stores the value of magic from an array of bytes.

I want to migrate it to Java, so far I have this:

int magic = stream[0];

But it is not working. I think that it is due to the length of the ints in Java and C++. Shall I use two bytes in the Java part to retrieve the proper magic number?

Manuelarte
  • 1,658
  • 2
  • 28
  • 47
  • What you are trying to do here, is slightly more complex in java than it is in C++, check this out http://stackoverflow.com/a/7619111/3447831 – Nagarz Jun 15 '15 at 14:56
  • 2
    An `int` in Java is 32-bit and always 32-bit. An `int` in C++ does not have to be 32-bit. – PaulMcKenzie Jun 15 '15 at 14:58

1 Answers1

0
byte[] stream = ...
ByteBuffer buf = ByteBuffer.wrap(stream);
buf.order(ByteOrder.LITTLE_ENDIAN);
int magic = buf.readInt();

See ByteBuffer. A java int is always 4 bytes signed, and per default java uses a BIG_ENDIAN byte order, so you might want to set a reversed order.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138