方法一
Java代码:
import java.nio.ByteBuffer;
import java.util.ArrayList;
float buffer = 0f;
ByteBuffer bbuf = ByteBuffer.allocate(4);
bbuf.putFloat(buffer);
byte[] bBuffer = bbuf.array();
bBuffer=this.dataValueRollback(bBuffer);
//数值反传
private byte[] dataValueRollback(byte[] data) {
ArrayList al = new ArrayList();
for (int i = data.length - 1; i >= 0; i--) {
al.add(data[i]);
}
byte[] buffer = new byte[al.size()];
for (int i = 0; i <= buffer.length - 1; i++) {
buffer[i] = al.get(i);
}
return buffer;
}
方法二
先用 Float.floatToIntBits(f)转换成int
再通过如下方法转成byte []
参考自
站长网http://www.software8.co/wzjs/java/2548.html
Java代码:
/**
* 将int类型的数据转换为byte数组 原理:将int数据中的四个byte取出,分别存储
*
* @param n int数据
* @return 生成的byte数组
*/
public static byte[] intToBytes2(int n) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (n >> (24 - i * 8));
}
return b;
}
/**
* 将byte数组转换为int数据
*
* @param b 字节数组
* @return 生成的int数据
*/
public static int byteToInt2(byte[] b) {
return (((int) b[0]) << 24) + (((int) b[1]) << 16)
+ (((int) b[2]) << 8) + b[3];
}