简体   繁体   中英

Using char as an unsigned 16 bit value in Java?

I need an unsigned 8 bit integer in Java, and char seems to be the only thing close to that. Although it's double the size, it's unsigned which makes it practical for what I want to use it for (writing a basic emulator which requires unsigned bytes). The problem is that I've heard other programmers say that one shouldn't use char in that manner and should just use int or so. Is this true, and why so?

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

使用byte表示经过一些次要转换的无符号8位整数是完全合理的,或者GuavaUnsignedBytes可以为您进行转换。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM