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

亡梦爱人 提交于 2020-01-03 15:31:31

问题


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:

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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/9793200/what-is-the-easiest-way-to-set-custom-binary-data-messages-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!