在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

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

best way to reverse bytes in an int in java

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.reversethat reverses every bit of an int

Integer.reverse有反转的每一点int

int numBitsReversed = Integer.reverse(num);

java.lang.IntegerAPI links

java.lang.Integer接口链接



Solution for other primitive types

其他原始类型的解决方案

There are also some Long, Character, and Shortversion of the above methods, but some are notably missing, e.g. Byte.reverse. You can still do things like these:

上述方法也有一些LongCharacterShort版本,但有些明显缺失,例如Byte.reverse。您仍然可以执行以下操作:

byte bitsRev = (byte) (Integer.reverse(aByte) >>> (Integer.SIZE - Byte.SIZE));

The above reverses the bits of byte aByteby promoting it to an intand 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 floator a double, there are Float.floatToIntBitsand Double.doubleToLongBitsthat you can use.

如果你想操作的位floatdoubleFloat.floatToIntBitsDouble.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 运算。