长期反转字节顺序 [英] Reverse bytes order of long

查看:208
本文介绍了长期反转字节顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,我需要扭转其字节顺序。例如: B1,B2,...,B8 我应该返回长,由的B8,B7,...,B1 。我如何使用位运算办呢?

I've got a long variable and I need to reverse its byte order. For example: B1, B2, ... , B8 I should return a long that consists of B8, B7, ..., B1. How can I do it by using bitwise operations?

推荐答案

您可以使用的 Long.reverseBytes(长)

或了解更多的方法,其中包括位运算,可以参考这个<一个href=\"http://stackoverflow.com/questions/1586882/how-do-i-convert-a-byte-to-a-long-in-java/1586920#1586920\">stack

Or for more methods which include bitwise operations, you can refer to this stack overflow question

继承人另一个你可能喜欢的方式,我还是建议以上,但它比按位好,你可以很容易犯错误。

Heres another method you may like, I'd still recommend the above but it's better than bitwise where you can easily make mistakes.

的ByteBuffer

byte[] bytes = ByteBuffer.allocate(8).putLong(someLong).array();
for (int left = 0, right = bytes.length - 1; left < right; ++left, --right) {
    byte temp = bytes[left]; 
    bytes[left]  = bytes[right]; 
    bytes[right] = temp;
}

我想从按位解决方案,引导你,因为他们很麻烦,很容易乱了,如果你不知道你在做什么......但按位应该是这样的:

I am trying to steer you away from bitwise solutions because they are cumbersome and very easy to mess up if you do not know what you are doing... But bitwise would look like this:

byte[] bytes = new byte[8];

// set the byte array from smallest to largest byte
for(int i = 0; i < 8; ++i) {
    byte[i] = (your_long >> i*8) & 0xFF;
}

// build the new long from largest to smallest byte (reversed)
long l = ((buf[0] & 0xFFL) << 56) |
         ((buf[1] & 0xFFL) << 48) |
         ((buf[2] & 0xFFL) << 40) |
         ((buf[3] & 0xFFL) << 32) |
         ((buf[4] & 0xFFL) << 24) |
         ((buf[5] & 0xFFL) << 16) |
         ((buf[6] & 0xFFL) <<  8) |
         ((buf[7] & 0xFFL) <<  0) ;

这篇关于长期反转字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆