简体   繁体   English

在Java中使用OR进行OR运算的问题?

[英]Issues with OR-ing with bytes in Java?

Let's say I have the following code in java 假设我在java中有以下代码

byte t = (byte) 0b10001000;
byte z = 0b00000000;
z = (byte) (t|z);

You'd think the output would be 10001000, however it ends up being -1111000 in String representation, the - sign being the first 1 of course, making it 11111000. If I do the same code but with the last bit in z as a 1, eg 00000001, and I perform the same operation, I get -1110111, or 11110111. I figure this is due to some conversion issue with the negatively signed byte t. 您认为输出将是10001000,但它最终在字符串表示中为-1111000, - 符号当然是第一个1,使其为11111000.如果我执行相同的代码但是将z中的最后一个位作为1,例如00000001,我执行相同的操作,我得到-1110111或11110111.我认为这是由于负符号字节t的一些转换问题。 Is there any way to avoid this? 有什么方法可以避免这种情况吗? Is there any way to have 10000000 work the same in an OR operation as 01000000? 有没有办法让10000000在OR操作中与01000000相同?

Java doesn't have unsigned types, so when you use binary notaion and set the sign bit things will not go as you expect ;-) Java没有无符号类型,所以当你使用二进制notaion并设置符号时,事情就不会像你期望的那样;-)

To emulate an unsigned type you need to work in the next size up. 要模拟未签名的类型,您需要在下一个版本中工作。

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

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