简体   繁体   English

如何在 Java 中为变量分配 2 个字节?

[英]How can I assign 2 bytes to a variable in Java?

How can I assign 2 bytes to a variable in Java?如何在 Java 中为变量分配 2 个字节? I know I can do this:我知道我可以这样做:

byte val = 2; // this is one byte with 0000 0010

But I need to assign 2 bytes to val.但我需要为 val 分配 2 个字节。 How can I do this?我怎样才能做到这一点?

As well as using an array of two bytes, you can use a short, which is guaranteed by the Java language spec to be 16 bits wide .除了使用两个字节的数组,您还可以使用 short, Java 语言规范保证它为16 位宽

short x = 0x1234s; // assigns 0x34 to the lower byte, 0x12 to the higher byte.

If you have two bytes that you want to combine into a short, you'll need shift the higher byte by 8 bits and combine them with bitwise or:如果您想将两个字节组合成一个短字节,则需要将高字节移动 8 位并将它们与按位组合或:

byte b1 = 0x12;
byte b2 = 0x34;
short x = ((short)b1 << 8) | b2;

If you want to assign different bits to a single byte variable, then you do that with the right-shift and bitwise or operators as well.如果您想为单个字节变量分配不同的,那么您也可以使用右移和按位或运算符来实现。 Bit n is identified by (1<<n).位 n 由 (1<<n) 标识。 0 is the first bit of the byte, 7 the last. 0 是字节的第一位,7 是最后一位。 So setting two bits is done like:所以设置两位是这样完成的:

byte b = (1<<3)|(1<<2); // b is set to 0000 1100

Are you looking for a byte array of length 2?您在寻找长度为 2 的字节数组吗? In this case:在这种情况下:

byte[] val = new byte[2];
val[0] = 2;
val[1] = something else;

You can store two values in one field using XOR :)您可以使用 XOR 将两个值存储在一个字段中:)

byte a, b, c;
a = 5;
b = 16;

c = a ^ b;

...

byte temp_a, temp_b;
temp_a = c ^ 16; /* temp_a == 5 */
temp_b = c ^ 5;  /* temp_b == 16 */

As you might have noticed, you need one of the original values to retrieve the other, so this technique is not as ... useful as the bit-shift method suggested.正如您可能已经注意到的那样,您需要一个原始值来检索另一个,因此该技术不像建议的位移位方法那样有用。

byte[] bytes = new byte[2];
bytes[0] = 2;
bytes[0] = 26;

使用字节数组、(短)整数或BitSet

Are you talking about assigning 2 bytes or 2 bits?您是在谈论分配 2 个字节还是 2 个位?

byte b = 5; //0000 0101

You may also want to try BitSet .您可能还想尝试BitSet

You might want to take a look at Javolution's Struct class.您可能想看看 Javolution 的 Struct 类。 http://javolution.org/target/site/apidocs/javolution/io/Struct.html http://javolution.org/target/site/apidocs/javolution/io/Struct.html

It lets you lay out structures with fixed length members and specific memory alignments.它使您可以使用固定长度的成员和特定的内存对齐来布置结构。 The implementation is backed by a ByteBuffer, so you can allocate it using direct memory if you are interacting with native code.该实现由 ByteBuffer 支持,因此如果您正在与本机代码交互,则可以使用直接内存分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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