1

I want to transform a long to binary code, then change some bits and get the long again. I have found this post Java long to binary but I still can't achieve what I want.

I think there is two ways to achieve my goal:

  1. Going from long to bitset and to long again
  2. Going from long to binary String and then to int array and then to long again
 public static long changeHalf(long x){
        int[] firstHalf = new int[32];
        int[] secondHalf = new int[32];
        int[] result = new int[64];


        String binaryOfLong = Long.toBinaryString(x);
        for (int i = 0; i < firstHalf.length; i++) {

        }

        for (int i = 0; i < secondHalf.length; i++) {
            result[i] = secondHalf[i];
        }
        for (int i = 0; i < firstHalf.length; i++) {
            result[i+32] = firstHalf[i];
        }

        String s = Arrays.toString(result);
        return Long.parseLong(s);
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
J.erome
  • 688
  • 7
  • 26

1 Answers1

4

Rather than converting a long to arrays of int, just use bitwise operations.

I want to swap the first 32 bits with the last 32 bits

That would be:

long result = ((x & 0xFFFFFFFF00000000l) >> 32) | ((x & 0x00000000FFFFFFFFl) << 32);

That masks off the first 32 bits, shifts them to the right, masks off the last 32 bits, shifts them to the left, and combines the result with | (OR).

Live example:

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        long x = 0x1000000020000000l;
        long result = ((x & 0xFFFFFFFF00000000l) >> 32) | ((x & 0x00000000FFFFFFFFl) << 32);
        System.out.printf("0x%016X\n", x);
        System.out.printf("0x%016X\n", result);
    }
}

Outputs:

0x1000000020000000
0x2000000010000000

More in the Bitwise and Bit Shift Operators tutorial.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Yes I have seen it right after, but I still have a question. If I give 12L, the result after the swap should be a big number like >1024 right ? But I still get 12 in return – J.erome Jun 10 '19 at 07:18