我以前有一小段代码:
import com.datastax.oss.driver.shaded.guava.common.primitives.Ints;
final long timeStamp = Instant.now().getEpochSecond();
final byte[] timeStampAsBytes = Ints.toByteArray((int) timeStamp);
注意,这个库有一个外部依赖项,还有一个cast,所以我决定重构它,使它更清晰一点。
final long timeStamp = Instant.now().getEpochSecond();
final byte[] timeStampAsBytes2 = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(timeStamp).array();
然而,令人相当惊讶的是,这两者其实并不相等!
final long timeStamp = Instant.now().getEpochSecond();
final byte[] timeStampAsBytes = Ints.toByteArray((int) timeStamp);
final byte[] timeStampAsBytes2 = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(timeStamp).array();
if (Arrays.equals(timeStampAsBytes, timeStampAsBytes2)) {
System.out.println("EQUAL");
} else {
System.out.println("NOT EQUAL");
}
final byte[] timeStampAsBytes = Ints.toByteArray((int) timeStamp);