在java中反转int中的字节的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3128148/
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
best way to reverse bytes in an int in java
提问by DEACTIVATIONPRESCRIPTION.NET
What's the best way to reverse the order of the 4 bytes in an int in java??
在java中反转int中4个字节的顺序的最佳方法是什么?
采纳答案by polygenelubricants
You can use Integer.reverseBytes
:
您可以使用Integer.reverseBytes
:
int numBytesReversed = Integer.reverseBytes(num);
There's also Integer.reverse
that reverses every bit of an int
也Integer.reverse
有反转的每一点int
int numBitsReversed = Integer.reverse(num);
java.lang.Integer
API links
java.lang.Integer
接口链接
public static int reverseBytes(int i)
- Returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.
public static int reverse(int i)
- Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.
public static int reverseBytes(int i)
- 返回通过反转指定 int 值的二进制补码表示中的字节顺序而获得的值。
public static int reverse(int i)
- 返回通过反转指定 int 值的二进制补码表示中的位顺序而获得的值。
Solution for other primitive types
其他原始类型的解决方案
There are also some Long
, Character
, and Short
version of the above methods, but some are notably missing, e.g. Byte.reverse
. You can still do things like these:
上述方法也有一些Long
、Character
和Short
版本,但有些明显缺失,例如Byte.reverse
。您仍然可以执行以下操作:
byte bitsRev = (byte) (Integer.reverse(aByte) >>> (Integer.SIZE - Byte.SIZE));
The above reverses the bits of byte aByte
by promoting it to an int
and reversing that, and then shifting to the right by the appropriate distance, and finally casting it back to byte
.
上面通过将 的位byte aByte
提升为 anint
并将其反转,然后向右移动适当的距离,最后将其转换回byte
。
If you want to manipulate the bits of a float
or a double
, there are Float.floatToIntBits
and Double.doubleToLongBits
that you can use.
如果你想操作的位float
或double
有Float.floatToIntBits
和Double.doubleToLongBits
,您可以使用。
See also
也可以看看
回答by yerlilbilgin
I agree that polygenelubricants's answer is the best one. But just before I hit that, I had the following:
我同意 polygenelubricants 的答案是最好的。但就在我打那个之前,我有以下几点:
int reverse(int a){
int r = 0x0FF & a;
r <<= 8; a >>= 8;
r |= 0x0FF & a;
r <<= 8; a >>= 8;
r |= 0x0FF & a;
r <<= 8; a >>= 8;
r |= 0x0FF & a;
return r;
}
shifting the input right, the output left by 8 bits each time and OR'ing the least significant byte to the result.
将输入右移,每次将输出左移 8 位,并将最低有效字节与结果进行 OR 运算。