title: Implementing a C style bitfield in Java
body: <p>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.</p>
  
  <p>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). </p>
  
  <pre class="lang-c prettyprint-override"><code>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;
  </code></pre>
  
  <p>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. </p>
  
  <p>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. </p>
  
  <p>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. </p>
  
  <p>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).</p>
  
  <p>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. </p>
  
  <p>Thank you for any help you can provide!</p>