How do I convert Long to byte[] and back in java

public byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x); return buffer.array(); } public long bytesToLong(byte[] bytes) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.put(bytes); buffer.flip();//need flip return buffer.getLong(); } Or wrapped in a class to avoid repeatedly creating ByteBuffers: public class ByteUtils { private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); public static byte[] longToBytes(long x) { buffer.putLong(0, … Read more

Why do these two multiplication operations give different results?

long oneYearWithL = 1000*60*60*24*365L; long oneYearWithoutL = 1000*60*60*24*365; Your first value is actually a long (Since 365L is a long, and 1000*60*60*24 is an integer, so the result of multiplying a long value with an integer value is a long value. But 2nd value is an integer (Since you are mulitplying an integer value with … Read more