如何在 Java 中为变量分配 2 个字节?我知道我可以做到这一点:
byte val = 2; // this is one byte with 0000 0010
但我需要为 val 分配 2 个字节。我该怎么做?
最佳答案
除了使用两个字节的数组外,您还可以使用一个短数组,即 guaranteed by the Java language spec to be 16 bits wide .
short x = 0x1234s; // assigns 0x34 to the lower byte, 0x12 to the higher byte.
如果你有两个字节想组合成一个短的,你需要 将高位字节移动 8 位,然后按位或组合它们:
byte b1 = 0x12;
byte b2 = 0x34;
short x = ((short)b1 << 8) | b2;
如果您想将不同的位分配给单个字节变量,那么您也可以使用右移和按位或运算符来实现。位 n 由 (1<byte b = (1<<3)|(1<<2); // b is set to 0000 1100
关于java - 我如何在 Java 中为变量分配 2 个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098097/