起因:想把一个float[]转换成内存数据,查了一下,下面两个方法可以将float转成byte[]。
方法二
先用 Float.floatToIntBits(f)转换成int
再通过如下方法转成byte []
方法三(这个是我在用的):
方法一
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<Byte> al = new ArrayList<Byte>();
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 []
/**
* 将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];
}
方法三(这个是我在用的):
/**
* 浮点转换为字节
*
* @param f
* @return
*/
public static byte[] float2byte(float f) {
// 把float转换为byte[]
int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (24 - i * 8));
}
// 翻转数组
int len = b.length;
// 建立一个与源数组元素类型相同的数组
byte[] dest = new byte[len];
// 为了防止修改源数组,将源数组拷贝一份副本
System.arraycopy(b, 0, dest, 0, len);
byte temp;
// 将顺位第i个与倒数第i个交换
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}
return dest;
}
/**
* 字节转换为浮点
*
* @param b 字节(至少4个字节)
* @param index 开始位置
* @return
*/
public static float byte2float(byte[] b, int index) {
int l;
l = b[index + 0];
l &= 0xff;
l |= ((long) b[index + 1] << 8);
l &= 0xffff;
l |= ((long) b[index + 2] << 16);
l &= 0xffffff;
l |= ((long) b[index + 3] << 24);
return Float.intBitsToFloat(l);
}