开发者

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 c开发者_高级运维lass?

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


Presumably, you mean implement it as a class which uses a larger data type and bounds checking, like this:

public class Unsigned24 {
    private static final MAX_UNSIGNED24 = Math.pow(2, 24) - 1;
    private static final MIN_UNSIGNED24 = 0;

    private final int value;

    public Unsigned24(int value) {
        if (value > MAX_UNSIGNED24 || value < MIN_UNSIGNED24)
            throw new IllegalArgumentException("value out of bounds: " + value);
        this.value = value;
    }

    public int getValue() {
        return value;
    }

// ... other methods, such as equals(), comparison, addition, subtraction, etc.
}

This would work, but might not be worth the trouble. Also, it doesn't really take only 24 bits of memory, but rather 32 plus the overhead for an object.

It really depends on your goals. Why do you want a 24-bit integer.

Is it just because you have bounds-constraints on the values? If so, you might want to do something like the above.

Is it because you have a lot of them, and want to save memory? If so, you might want to build some class that abstracts an array of 24-bit integers, and internally saves them consecutively in a byte-array.

Is it because you are interfacing with some hardware or network interface that expects exactly 24 bits? In that case, you might want to look at the java.nio classes.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜