java float 转byte[]

学习笔记,转自http://tjmljw.iteye.com/blog/1767716

 1 public class float2bytes
 2 {
 3 
 4     /**
 5      * 浮点转换为字节
 6      * 
 7      * @param f
 8      * @return
 9      */
10     public static byte[] float2byte(float f) {
11         
12         // 把float转换为byte[]
13         int fbit = Float.floatToIntBits(f);
14         
15         byte[] b = new byte[4];  
16         for (int i = 0; i < 4; i++) {  
17             b[i] = (byte) (fbit >> (24 - i * 8));  
18         } 
19         
20         // 翻转数组
21         int len = b.length;
22         // 建立一个与源数组元素类型相同的数组
23         byte[] dest = new byte[len];
24         // 为了防止修改源数组,将源数组拷贝一份副本
25         System.arraycopy(b, 0, dest, 0, len);
26         byte temp;
27         // 将顺位第i个与倒数第i个交换
28         for (int i = 0; i < len / 2; ++i) {
29             temp = dest[i];
30             dest[i] = dest[len - i - 1];
31             dest[len - i - 1] = temp;
32         }
33         
34         return dest;
35         
36     }
37     
38     /**
39      * 字节转换为浮点
40      * 
41      * @param b 字节(至少4个字节)
42      * @param index 开始位置
43      * @return
44      */
45     public static float byte2float(byte[] b, int index) {  
46         int l;                                           
47         l = b[index + 0];                                
48         l &= 0xff;                                       
49         l |= ((long) b[index + 1] << 8);                 
50         l &= 0xffff;                                     
51         l |= ((long) b[index + 2] << 16);                
52         l &= 0xffffff;                                   
53         l |= ((long) b[index + 3] << 24);                
54         return Float.intBitsToFloat(l);                  
55     }
56 
57 
58 public static void main(String[] args)
59 {
60 //float2bytes f2b = new float2bytes();
61 byte[] b = new byte[4];
62 float f = 11.21f;
63 b=float2byte(f);
64 for(int i=0;i<b.length;i++)
65 {
66 System.out.println(b[i]);
67 }
68 
69 System.out.println(byte2float(b,0));
70 }
71 
72 }
原文地址:https://www.cnblogs.com/ning1121/p/3482591.html