我想确保严格正长的异或运算只能产生严格正长。
我的问题基于以下Java代码:
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);
}
}
谁能提供一些理论上的答案?
最佳答案
不变式1:正整数的最高有效位为零。
不变式2:0 XOR 0 = 0。
结论:正整数XOR正整数=正整数。