WritableUtils { public static void convertFloatToByte(float[] floatArray, byte[] byteArray) { Assert.argument(4 * floatArray.length == byteArray.length, "4 * floatArray.length == byteArray.length"); int bi = 0; for (float aFloat : floatArray) { int intBits = Float.floatToIntBits(aFloat); byteArray[bi++] = (byte) ((intBits >>> 24) & 0xFF); byteArray[bi++] = (byte) ((intBits >>> 16) & 0xFF); byteArray[bi++] = (byte) ((intBits >>> 8) & 0xFF); byteArray[bi++] = (byte) ((intBits >>> 0) & 0xFF); } }  static void convertByteToFloat(byte[] byteArray, float[] floatArray); static void convertFloatToByte(float[] floatArray, byte[] byteArray);  }
@Test(expected = IllegalArgumentException.class) public void testConvertFloatToByte_wrongSize() throws Exception { float[] floatArray = new float[]{0.12f, 0.42f, 5.67f}; byte[] byteArray = new byte[3]; WritableUtils.convertFloatToByte(floatArray, byteArray); }
@Test public void testConvertFloatToByte() throws Exception { float[] floatArray = new float[]{0.12f, 0.42f, 5.67f}; byte[] byteArray = new byte[3 * 4]; WritableUtils.convertFloatToByte(floatArray, byteArray); DataInputStream in = new DataInputStream(new ByteArrayInputStream(byteArray)); assertEquals(0.12f, in.readFloat(), 0.000001f); assertEquals(0.42f, in.readFloat(), 0.000001f); assertEquals(5.67f, in.readFloat(), 0.000001f); }