在Java中实现C样式位域 [英] Implementing a C style bitfield in Java

查看:68
本文介绍了在Java中实现C样式位域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,就是我有点被困住了,一位同事告诉我,这将是寻求帮助的好地方.

I have a problem that I am a bit stuck on and I was informed by a colleague that this would be a good place to seek help.

我正在尝试在Java中实现C风格的位域.这是一个粗略的示例(此刻我还没有实际的代码).

I am trying to implement a C style bitfield in Java. Here is a rough example (I do not have the actual code in front of me at this moment).

typedef union
{
  typedef struct
  {
     unsigned short a :1;
     unsigned short b :1;
     unsigned short c :2;
     unsigned short d :10;
  } bitfield;

  unsigned short bitmap;
}example_bitfield;

我有很多来自遗留代码的相似样式位域.我需要提出一种等效的Java方法的原因是,我正在开发将使用Java与其他使用UDP的旧应用程序进行通信的代码.

I have a good bit of similar style bitfields from legacy code. The reason that I need to come up with an equivalent method for Java is that I am working on code that will use Java to communicate with other legacy applications using UDP.

我没有重写代码的选择.我知道这种方法不是可移植的,存在字节顺序问题(以及填充/对齐等),如果我能够重写代码,可以采用更好的方法.不幸的是,我需要针对这个非常具体的问题的答案.系统是封闭的,因此我不必担心编译器/操作系统/ect的每种可能组合.

I do not have the option of rewriting the code. I am aware that this approach is not portable, has endianness issues (and padding/alignment, ect), and could be done a better way if I were able to rewrite the code. Unfortunately I need an answer to this very specific problem. The system is closed and so I do not need to worry about every single possible combination of compilers/operating systems/ect.

使用Java EnumSet的方法将不起作用,因为我认为这只会将每个值设为一位.我需要能够将d的值打包(例如占用10位).

The approach of using a Java EnumSet will not work because I believe that will only allow for each value to be one bit. I need to be able to pack values with for instance the value of d occupying 10 bits.

我了解Java Bitset,但是它有局限性.我使用的是Java的较旧版本,因此我没有一些较新的Java Bitset方法(即valueOf方法可能肯定会有所帮助).

I know about the Java Bitset but it has limitations. I am using an older version of Java, and so I do not have some of the newer Java Bitset methods (Namely the valueOf methods which would probably surely help).

有人对如何使其尽可能易于管理有任何想法吗?我的通讯需要实现10多个位域.

Does anyone have any ideas of how to make this as manageable as possible? I have over 10 bitfields that I need to implement for my communications.

感谢您提供的任何帮助!

Thank you for any help you can provide!

推荐答案

由于UDP只接受字节数组,因此可以以任何合适的方式声明Java类,并且唯一的关键步骤是定义其序列化和反序列化方法:

Since UDP accepts only byte arrays, you can declare a Java class in any suitable way and the only critical step is to define its serialization and deserialization methods:

class example_bitfield {
  byte a;
  byte b;
  byte c;
  short d;

  public void fromArray(byte[] m) {
    byte b0=m[0];
    byte b1=m[1];
    a=b0>>>7;
    b=(b0>>6)&1;
    c=(b0>>4)&3;
    d=(b0&0xF<<6)|(b1>>>2);
  }
  public void toArray(byte[] m) {
    m[0]=(a<<7)|(b<<6)|(c<<4)|(d>>>6);
    m[1]=(d&0x3F)<<2;
  }
}

这篇关于在Java中实现C样式位域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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