Skip to content

Instantly share code, notes, and snippets.

@akhawaja
Created July 8, 2017 20:59
Show Gist options
  • Save akhawaja/9133f3defa2121e80e2a26911263ea8e to your computer and use it in GitHub Desktop.
Save akhawaja/9133f3defa2121e80e2a26911263ea8e to your computer and use it in GitHub Desktop.
Some utility functions for handling byte conversions.
package com.amirkhawaja;
import java.nio.ByteBuffer;
public final class ByteUtils {
private ByteUtils() {
}
public static long stringToLong(String s) {
return ByteBuffer.wrap(s.getBytes()).getLong();
}
public static byte[] longToBytes(long x) {
final ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(0, x);
return buffer.array();
}
public static long bytesToLong(byte[] bytes) {
final ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes, 0, bytes.length);
buffer.flip();//need flip
return buffer.getLong();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment