Skip to content

Instantly share code, notes, and snippets.

@mjwillson
Created April 30, 2013 16:33
Show Gist options
  • Save mjwillson/5489902 to your computer and use it in GitHub Desktop.
Save mjwillson/5489902 to your computer and use it in GitHub Desktop.
convert between float arrays and byte arrays
package randomindexing;
/* Helpers for encoding various primitive arrays as byte arrays.
(Why this isn't in the stdlib I have no idea! feel free to replace
with some existing library implementation...)
All encodings use little-endian byte order.
I benchmarked using
ByteBuffer.wrap(b).order(LITTLE_ENDIAN).asFloatBuffer().get(f),
but it's around 3 times slower even on big input.
*/
public class Encoding {
public static void floatsToBytes(float[] floats, byte[] bytes) {
assert floats.length * 4 == bytes.length;
for (int i = 0; i < floats.length; i++) {
int x = Float.floatToRawIntBits(floats[i]);
bytes[i*4] = (byte) (x & 0xff);
bytes[i*4+1] = (byte) ((x >>> 8) & 0xff);
bytes[i*4+2] = (byte) ((x >>> 16) & 0xff);
bytes[i*4+3] = (byte) (x >>> 24);
}
}
public static byte[] floatsToBytes(float[] floats) {
byte[] bytes = new byte[floats.length * 4];
floatsToBytes(floats, bytes);
return bytes;
}
public static void bytesToFloats(byte[] bytes, float[] floats) {
assert floats.length * 4 == bytes.length;
for (int i = 0; i < floats.length; i++) {
int x = bytes[i*4] & 0xff;
x += (bytes[i*4+1] & 0xff) << 8;
x += (bytes[i*4+2] & 0xff) << 16;
x += (bytes[i*4+3] & 0xff) << 24;
floats[i] = Float.intBitsToFloat(x);
}
}
public static float[] bytesToFloats(byte[] bytes) {
float[] floats = new float[bytes.length / 4];
bytesToFloats(bytes, floats);
return floats;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment