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

问题描述 投票:1回答:3

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

java byte emulation unsigned
3个回答
3
投票

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


2
投票

在Java中:

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

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

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

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

字符:[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进行转换。


2
投票

使用byte来表示无符号8位整数并进行一些微小转换是完全合理的,或者GuavaUnsignedBytes会转换给你。

© www.soinside.com 2019 - 2024. All rights reserved.