Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse bytes order of long

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?

like image 328
Aviram Avatar asked Jan 16 '23 21:01

Aviram


2 Answers

you can use Long.reverseBytes(long)

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) ;
like image 184
Serdalis Avatar answered Jan 26 '23 05:01

Serdalis


You might want to use Long.reverseBytes instead of using bitwise operations. See the Java Reference for details.

Otherwise, you could have a look at the JDK sources (src.zip in your JDK folder) in Long.java but mind the copyright by Oracle.

like image 35
Matthias Avatar answered Jan 26 '23 03:01

Matthias