How to write many small unions from C in Java

I rewrote the C code in Java. The core of the C source code is the HW shell. In C, we used many unions for each HW register, for example:

typedef union RegIntStatus { u8 reg; struct { u8 bit0_abc:1; u8 bit1_cde:1; u8 bit2_xyz:1; u8 bit3_7_rsvd:5; } bits; } regABC; 

then we used it as

 regABC r; r.reg=0 r.bits.bit0_abc=1; call(r.reg) 

Imagine that there are many of these registers. Let's say 40. How to implement it in java without having 40 class files? I thought to create one class, for example

 univerasl_reg<T> { // where T will be some "enum" public byte b; public byte set(T bit_mask,bool val) { // here is compile error it does not know variable bit_mask.v if(val) {b |= bit_mask.v} else b &= bit_mask.v ^ 0xFF; } } 

then one file can contain several enumerations of the type:

 public static enum RegTst{ b1_abc(0x01), b2_xyz(0x02), b3_klm(0x04); public byte v; RegTst(int val){ v = (byte)val; } } 

then I would use it like:

 univerasl_reg<RegTst> rt1; rt1.set(RegTst.b2_xyz,1) call(rt1.b) 

But this does not work, because it seems that I can not use the enum.v variable in univerasl_reg. This gives "Java canot find symbol v". You know why? You know how to encode registers to have - preferably one file
- type control between different registers (e.g.

  new univerasl_reg <RegTst> .set (RegTst_OTHER.b2_xyz, 1) 
will result in an error since I am not using RegTst, but RegTst_OTHER)
- and mnemonic for bits (for example, RegTst.b1_abc)
+7
java enums union
source share
1 answer

Java Generics is a function of only a static type system. When you accept any T for a type parameter, a system of a static type has no reason to believe that this type has an instance variable v . Your choice of enumerations complicates the situation, because enumerations cannot have an arbitrary superclass.

I would suggest the following:

  • rely on polymorphism and hide v behind the method;
  • declare an interface using this method;
  • make all transfers implemented interface;
  • use the interface as the upper bound on T

In code:

 public interface Mask { byte v(); } public class UniversalReg<T extends Mask> { public byte b; public byte set(T mask, boolean val) { if (val) b |= mask.v(); else b &= ~mask.v(); } } public enum RegTst implements Mask { b1_abc(0x01), b2_xyz(0x02), b3_klm(0x04); private final byte v; private RegTst(int val) { v = (byte)val; } @Override public byte v() { return v; } } 
+2
source share

All Articles