原文网址:http://tjmljw.iteye.com/blog/1767716
起因:想把一个float[]转换成内存数据,查了一下,下面两个方法可以将float转成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 []
- 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;
- }
-
- public static int byteToInt2(byte[] b) {
- return (((int) b[0]) << 24) + (((int) b[1]) << 16)
- + (((int) b[2]) << 8) + b[3];
- }
方法三(这个是我在用的):
- public static byte[] float2byte(float f) {
-
-
- 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;
-
- for (int i = 0; i < len / 2; ++i) {
- temp = dest[i];
- dest[i] = dest[len - i - 1];
- dest[len - i - 1] = temp;
- }
-
- return dest;
-
- }
-
- 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);
- }
2013-05-06 add
title Java基本类型与byte数组之间相互转换
from http://blog.sina.com.cn/s/blog_7a35101201012n0b.html
【转】java中float与byte[]的互转 -- 不错
原文:http://www.cnblogs.com/wi100sh/p/5171013.html