I’m trying to send and receive a byte stream in which certain ranges of bytes represent different pieces of data. I’ve found ways to convert single primitive datatypes into bytes, but I’m wondering if there’s a straightforward way to place certain pieces of data into specified byte regions.
For example, I might need to produce or read something like the following:
byte 1 - int
byte 2-5 - int
byte 6-13 - double
byte 14-21 - double
byte 25 - int
byte 26-45 - string
Any suggestions would be appreciated.
Try DataOutputStream/DataInputStream or, for arrays, the ByteBuffer class.
For storing the integer in X bytes, you may use the following method. If you think it is badly named, you may use the much less descriptive
i2osname which is used in several (crypto) algorithm descriptions. Note that the returned octet string uses Big Endian encoding of unsigned ints, which you should specify for your protocol.EDIT before storing the string, think of a padding mechanism (spaces would be most used), and character-encoding e.g.
String.getBytes(Charset.forName("ASCII"))or"Latin-1". Those are the most common encodings with a single byte per character. Calculating the size of “UTF-8” is slightly more difficult (encode first, add 0x20 valued bytes at the end usingByteBuffer).