什么是Java中设置自定义的二进制数据信息的最简单的方法? [英] What is the easiest way to set custom binary data messages in Java?

查看:346
本文介绍了什么是Java中设置自定义的二进制数据信息的最简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C#的世界即将和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:

正如你所看到的,一定整数值需要投入3位的插槽。其他值是单位标志,或其他尺寸领域。从我看过,我应该在一个较大的原始的工作,如建筑用逐位运营商在整数的二进制字节。是否有其他方法吗?我按照一些例子,我发现其他地方,如(注:本例中不符合上述图形),以获得结构化的第一个字节:

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);

有没有更好的方式来构建这些字节?我怎么上4字节字段使用?多头?

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

推荐答案

您也许能够使用的 的ByteBuffer 描述如这里。它应该更容易操纵字节数组,尤其是考虑之类的东西字节顺序考虑。

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.

这篇关于什么是Java中设置自定义的二进制数据信息的最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆