在Java中使用char作为无符号16位值?

时间:2013-05-29 08:31:23

标签: java byte emulation unsigned

我需要Java中的无符号8位整数,而char似乎是唯一接近它的东西。虽然它的大小是它的两倍,但是它是无符号的,这使得我想要用它来实现它(编写一个需要无符号字节的基本仿真器)。问题是我听过其他程序员说不应该以这种方式使用char,而应该只使用int。这是真的,为什么会这样呢?

3 个答案:

答案 0 :(得分:3)

如果需要无符号8位整数,请使用byte。很容易在arithemtic操作(实际上是重要的标记)中将其作为byteValue & 0xFF

进行无符号标记

答案 1 :(得分:2)

使用byte表示无符号8位整数并进行一些小转换,或Guava UnsignedBytes转换给您是完全合理的。

答案 2 :(得分:2)

在Java中:

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

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

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

字节:[ - 2 ^ 7,2 ^ 7 - 1]

char:[0,2 ^ 16 - 1]

你想要一个无符号的8位整数意味着你想要一个介于[0,2 ^ 8 - 1]之间的值。显然选择short / int / long / char。

尽管char可以被视为无符号整数,但我认为将char用于除字符之外的任何东西都是一种糟糕的编码风格。

例如,

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
}

}

最好使用short / int / long进行转换。