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.
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;
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.
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.
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.
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).
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!
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;
}
}