java 从 int 变量中获取两个低字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4826453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:13:14  来源:igfitidea点击:

Get two lower bytes from int variable

javabitwise-operators

提问by Damir

I have some data in intvariables in Java (range between 0 and 64000). How to convert to byte this integer? I need just two lower bytes from int(range is ok). How to extract this?

int在 Java中的变量中有一些数据(范围在 0 到 64000 之间)。如何将此整数转换为字节?我只需要来自int(范围可以)的两个低字节。如何提取这个?

回答by templatetypedef

You can get the lowest byte from the integer by ANDing with 0xFF:

您可以通过 AND 运算从整数中获取最低字节0xFF

byte lowByte = (byte)(value & 0xFF);

This works because 0xFFhas zero bits everywhere above the first byte.

这是有效的,因为0xFF在第一个字节上方的任何地方都有零位。

To get the second-lowest-byte, you can repeat this trick after shifting down all the bits in the number 8 spots:

要获得第二低的字节,您可以在将数字 8 位中的所有位向下移后重复此技巧:

byte penultimateByte = (byte)((value >> 8) & 0xFF);

回答by Mubashar

You don't have to do AND operation to get the lower byte just cast it to the byte and get the lower byte in the byte variable.

您不必执行 AND 操作来获取低字节,只需将其转换为字节并获取字节变量中的低字节即可。

try following both will give you same result

尝试遵循两者会给你相同的结果

short value = 257;
System.out.println(value);
byte low = (byte) value;
System.out.println("low: " + low);
byte high = (byte)(value >> 8);
System.out.println("high: " + high);

value = 257;
System.out.println(value);
low = (byte) (value & 0xFF);
System.out.println("low: " + low);
high = (byte) ((value >> 8) & 0xFF);
System.out.println("high: " + high);

or try it on Ideone.com

或在Ideone.com试用