简体   繁体   English

Java 字节数组中的无符号字节

[英]unsigned bytes in Java byte array

This may seem like an easy question, but I'm so confused.这似乎是一个简单的问题,但我很困惑。

byte[] bArray = new byte[]{(byte) (0x80 & 0xff)};
System.out.println(bArray[0]);

and my output is -128.我的输出是-128。 Why?为什么? How can I rewrite this so that the byte array contains 128?如何重写它以便字节数组包含 128? I thought that the 0xff made it unsigned.我认为0xff使它未签名。 Thanks for your help!感谢您的帮助!

I thought that the 0xff made it unsigned.我认为 0xff 使它未签名。

Well, it does, sort of - it promotes it to an int , and keeps just the last 8 bits.嗯,它确实,有点 - 它将它提升为int ,并且只保留最后 8 位。

However, you're then casting the result of that back to a byte , and a byte in Java is always signed.但是,您随后将其结果转换回一个byte ,并且 Java 中的一个byte始终是有符号的。 (It's annoying, but it's the way it is.) So you might as well just have written: (这很烦人,但事情就是这样。)所以你不妨这样写:

byte[] bArray = { (byte) 0x80 };

The result would be exactly the same.结果将完全相同。

You're storing the bit pattern you want to store (10000000) so if you're transmitting this elsewhere, you don't need to worry... it's just when you're viewing it as a byte in Java that it's annoying.您正在存储您想要存储的位模式 (10000000),因此如果您将其传输到其他地方,则无需担心……只是当您在 Java 中将其视为一个byte时,这很烦人。

Value range of byte according Java Language Specification 4.2.1根据Java 语言规范 4.2.1的字节值范围

For byte, from -128 to 127, inclusive对于字节,从 -128 到 127,包括

so there is no way (in Java) that a byte will hold (byte) 128.所以(在 ​​Java 中)一个字节不可能保存(字节)128。

You can cast the byte to an int and apply & 0xff to get the unsigned representation of the byte (as an int).您可以将字节转换为 int 并应用& 0xff来获取字节的无符号表示(作为 int)。 But if you cast it back to an byte it will again be interpreted as being a signed value between -128 and 127...但是如果你将它转换回一个字节,它将再次被解释为 -128 和 127 之间的有符号值......

If you are only concerned with printing:如果您只关心打印:

System.out.println(bArray[0] & 0xff);

or, for hexadecimal或者,对于十六进制

System.out.printf("0x%02x\n", bArray[0]);

My answer is attached in the big picture我的答案附在大图中在此处输入图片说明

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

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