Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to set custom binary data messages in Java?

Coming from the world of C# and brushing up on Java, I have learned that there are no unsigned bytes/ints. I am trying to find out what is the easiest way build up custom binary messages such as the following example:

enter image description here

As you can see, certain integer values need to put into a 3 bit slot. others values are single bit flags, or other size fields. From what I have read, I should work in the "next larger" primitive, such as building binary bytes in integers using bit wise operators. Are there other ways? I have followed some examples I found elsewhere such as (Note: this example does not match the graphic above) to get the first byte structured:

shiftedValue1 = (value1 & 0xFF) << 5;
shiftedValue2 = (Value2 & 0xFF) << 2;
shiftedValue3 = (Value3 & 0xFF) << 1;
shiftedValue4 = (Value4 & 0xFF);
finalvalue = (shiftedValue1 & 0xFF) | (shiftedValue2 & 0xFF) | (shiftedValue3 & 0xFF) | (shiftedValue4 & 0xFF);

Is there a better way to construct these bytes? What do I use on 4 Byte fields? Longs?

like image 200
kuhnto Avatar asked Nov 05 '22 03:11

kuhnto


2 Answers

Seems like this would be easier to do using either byte[] (byte arrays) or BitSets.

like image 117
Matt Ball Avatar answered Nov 10 '22 18:11

Matt Ball


You might be able to use ByteBuffer as described e.g. here. It should make it easier to manipulate the byte array, especially taking things like endianess into account.

like image 44
thkala Avatar answered Nov 10 '22 17:11

thkala