package test;public class Test { public static void main(String[] args) throws Exception { Float f = new Float(123.456f); byte bt = f.byteValue(); System.out.println(bt); } }输出:123
抱歉,我要的是一个byte数组而不是一个byte
可以先将float转化为String对象,然后用String对象的getBytes()方法,但是结果好像是返回的对应的ASCII码,例如1返回49.public class Test { public static void main(String[] args) throws Exception { Float f = new Float(123.456f); String s = f.toString(); byte[] b = s.getBytes(); for (byte by : b) { System.out.println(by); } } }输出; 49 50 51 46 52 53 54
OK,抱歉我没说清楚,我要的是一个4字节的byte数组, 既:一个单精度浮点数站4个位的十六进制数据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; }上面因是用了java.nio的类库,所以在j2me中无法使用,故只能在java.lang的基类库中调用,谢谢
使用 Float.floatToRawIntBits 先转成与 int 值相同位结构的 int 类型值,再根据 Big-Endian 或者是 Little-Endian 转成 byte 数组。
先用 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]; } }
package test;public class Test { public static void main(String[] args) throws Exception {
Float f = new Float(123.456f);
byte bt = f.byteValue();
System.out.println(bt);
}
}输出:123
Float f = new Float(123.456f);
String s = f.toString();
byte[] b = s.getBytes();
for (byte by : b) {
System.out.println(by);
}
}
}输出;
49
50
51
46
52
53
54
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;
}上面因是用了java.nio的类库,所以在j2me中无法使用,故只能在java.lang的基类库中调用,谢谢
先用 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];
}
}