了解Java包含或运算符(|) [英] Understanding Java Inclusive or Operator ( | )
问题描述
我正在尝试解决此问题:我有一个 byte 值(1个字节),我需要将此值转换为一个 long 值(8个字节) .但是我想要的只是将long变量的第一个字节替换为我之前拥有的字节值.
I'm trying to solve this problem: I have a byte value (1 byte) and I need to transform this value into a long value (8 bytes). But what I want is just replace the first byte of the long variable with the byte value I had before.
一个例子:
My Byte Value: 11001101
My Long Value: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
What I want: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 11001101
就这么简单!
我正在尝试执行此操作(示例):
I'm trying to do this (example):
byte b = -112;
long l = 0;
l = l | b;
System.out.println(l);
但是我得到的结果是-112!以我的理解,java位或运算符应对long值的第一个字节和该字节值进行或"运算.取而代之的是,or运算符将字节值的2补码表示形式复制到long值中,而这不是我想要的.
But I get the result -112! In my understanding, the java bit or operator should do an "or" with the first byte of the long value and the byte value. Instead, the or operator is copying the 2-complement representation of the byte value into the long value, and this is not what I want.
在这种情况下,我期望的结果是144,因为-112是10010000,考虑无符号值时,它是144.
The result I was expecting in that case was 144, since -112 is 10010000, which is 144 when considering a unsigned value.
希望您能理解我.谢谢!
Hope you understand me. Thanks!
推荐答案
此处发生的是将b
强制转换为long
,这是通过符号扩展完成的:有效位(1)被重复,因此7 11111111
个字节用作填充.此处的补救方法是使用按位和(&
):
What happens here is that b
is cast to long
, and this is done via sign extension: the most-significant bit (1) is repeated, hence 7 11111111
bytes are used as padding. The remedy here is to explicitly consider only the 8 least-significant bits in the resulting value, using a bitwise and (&
):
l = l | ((long)b & 0xff);
这篇关于了解Java包含或运算符(|)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!