I need something similar to Python's struct module for a Java project. I would like to pack integer (and perhaps floats and doubles as well) into byte arrays. Furthermore, I want to choose the endianness and generally have full control over how this is done because I need to send this data to some hardware which will be running code in another language.
Asked
Active
Viewed 4,079 times
2
-
1Maybe something like: http://docs.oracle.com/javase/1.5.0/docs/api/java/nio/ByteBuffer.html? – mowwwalker Nov 20 '12 at 04:03
-
Maybe you can just use Python? Probably not, though. SO sorry. – Keith Nov 20 '12 at 04:27
-
Exactly like that Walkerneo. Want to put that in an answer and maybe flesh it out a bit for anybody reading this question so I can check it off as the accepted answer? – Void Star Nov 20 '12 at 04:36
-
@BigEndian, I'll put it as an answer. Lemme play with it a bit first before the fleshing-out though :P – mowwwalker Nov 20 '12 at 04:42
2 Answers
4
From here: Convert 4 bytes to int, you can use java.nio.ByteBuffer

Community
- 1
- 1

mowwwalker
- 16,634
- 25
- 104
- 157
3
For an int var you can take each byte of the int and put on the array. Like that:
int info = 123456789;
byte [] data = new byte[100];
data[0] = (byte) ((info>>24) & 0xff);
data[1] = (byte) ((info>>16) & 0xff);
data[2] = (byte) ((info>>8) & 0xff);
data[3] = (byte) ((info) & 0xff);
int out = 0;
out = ((data[0]&0xff)<<24) | ((data[1]&0xff)<<16) | ((data[2]&0xff)<<8) | data[3]&0xff);
System.out.println("info " + info);
System.out.println("out " + out);
For a float or double you can't do like that directly. It's necessary convert your var to an int. It can be done using the methods Float.floatToRawIntBits() or Double.doubleToRawLongBits() .

Derzu
- 7,011
- 3
- 57
- 60
-
1Better use [`floatToRawIntBits()`](http://docs.oracle.com/javase/6/docs/api/java/lang/Float.html#floatToRawIntBits%28float%29) or [`doubleToRawLongBits()`](http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#doubleToRawLongBits%28double%29) instead of fooling around with "multiplying by an constant like 1000000"... – glglgl Nov 20 '12 at 08:51
-
@glglgl thanks, using floatToRawIntBits() is really better. I will upgrade my answer. – Derzu Nov 20 '12 at 12:12