Custom Data-type in Java

For an application I need to have an unsigned data-type with 24 bits. Unfortunately such a data type is not available in Java. I’m planning to implement it as a new class.But I’m not sure about the performance of such an implementation.

Is it advisable to write my own class?

If it is advisable, is it possible to good performance?

Answer

If you want to save space, you could use int for caluclation and map the least significant 3 bytes to a byte[] or just three bytes:

  public static byte[] convert(int i) {
    return new byte[]{ (i & 0xff0000) >> 16, (i & 0xff00) >> 8, (i & 0xff) };
  }

  public static int convert(byte[] b) {
    if (b == null && b.length != 3)
      throw new IllegalArgumentException();

      return (b[2] << 16) | (b[1] << 8) | b;
  }

(can’t verify if it is bug free but at least it should give an idea)

Leave a Reply

Your email address will not be published. Required fields are marked *