Using char as an unsigned 16 bit value in Java?

那年仲夏 提交于 2019-12-06 16:29:15

If you need an unsigned 8 bit integer then use byte. It's easy to make it unsigned in arithemtic operations (where actually sign matters) as byteValue & 0xFF

In Java:

long: [-2^63 , 2^63 - 1]

int: [-2^31 , 2^31 - 1]

short: [-2^15 , 2^15 - 1]

byte: [-2^7 , 2^7 - 1]

char: [0 , 2^16 - 1]

You want an unsigned 8 bit integer means you want a value between [0, 2^8 - 1]. It is clearly to choose short/int/long/char.

Although char can be treated as an unsigned integer, I think It's a bad coding style to use char for anything but characters.

For example,

public class Test {
public static void main(String[] args) {
    char a = 3;
    char b = 10;

    char c = (char) (a - b);
    System.out.println((int) c); // Prints 65529
    System.out.println((short) c); // Prints -7

    short d = -7;
    System.out.println((int) d); // Prints -7, Please notice the difference with char
}

}

It is better to use short/int/long with conversion.

Wudong

It is totally reasonable to use byte to represent an unsigned 8 bit integer with some minor conversion, or Guava's UnsignedBytes do the conversion to you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!