Search code examples
javabinarybinary-operators

Ensuring that an XOR operation on strictly positive longs only yield strictly positive longs


I want to ensure that an XOR operation on strictly positive longs only yields strictly positive longs.

My question is base on the following java code:

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;

public class Test {

    static Random r = new Random();

    static class Data {
        long id = Math.abs(r.nextLong());

        @Override
        public String toString() {
            return "Data {" + "id=" + id + '}';
        }
    }

    public static void main(String[] args) {
        List<Data> data = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            data.add(new Data());
        }

        final String password = "don't you ever tell them";

        byte[] passwordBytes = password.getBytes();
        long[] passwordLongs = new long[passwordBytes.length / 8];

        for (int i = 0; i < passwordLongs.length; i++) {
            ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
            byte[] chunk = new byte[Long.BYTES];
            System.arraycopy(passwordBytes, i * Long.BYTES, chunk, 0, Long.BYTES);
            buffer.put(chunk);
            buffer.flip();//need flip
            passwordLongs[i] = buffer.getLong();
        }

        System.out.println(data);

        ListIterator<Data> encryptIterator = data.listIterator();
        while (encryptIterator.hasNext()) {
            Data next = encryptIterator.next();
            next.id = next.id ^ passwordLongs[(encryptIterator.nextIndex() - 1) % passwordLongs.length];//XOR here
        }

        System.out.println(data);
    }
}

Can anyone please provide an answer possibly with some theory?


Solution

    • Invariant 1: a positive integer's most significant bit is zero.

    • Invariant 2: 0 XOR 0 = 0.

    Conclusion: positive integer XOR positive integer = positive integer.