1 public class TypeConvert {
2
3 /**
4 * 整数到字节数组的转换
5 */
6 public static byte[] intToByte(int number) {
7
8 int temp = number;
9 byte[] b = new byte[4];
10 for (int i = b.length - 1; i > -1; i--) {
11 b[i] = new Integer(temp & 0xff).byteValue(); // 将最高位保存在最低位
12 temp = temp >> 8; // 向右移8位
13 }
14 return b;
15 }
16
17 /**
18 * 字节数组到整数的转换
19 * @param b
20 * @return
21 */
22 public static int byteToInt(byte[] b) {
23 int s = 0;
24 for (int i = 0; i < 3; i++) {
25 if (b[i] >= 0)
26 s = s + b[i];
27 else
28
29 s = s + 256 + b[i];
30 s = s * 256;
31 }
32 if (b[3] >= 0) // 最后一个之所以不乘,是因为可能会溢出
33 s = s + b[3];
34 else
35 s = s + 256 + b[3];
36 return s;
37 }
38
39 /**
40 * 字符到字节转换
41 * @param ch
42 * @return
43 */
44 public static byte[] charToByte(char ch) {
45 int temp = (int) ch;
46 byte[] b = new byte[2];
47 for (int i = b.length - 1; i > -1; i--) {
48 b[i] = new Integer(temp & 0xff).byteValue(); // 将最高位保存在最低位
49 temp = temp >> 8; // 向右移8位
50 }
51 return b;
52 }
53
54 /**
55 * 字节到字符转换
56 * @param b
57 * @return
58 */
59 public static char byteToChar(byte[] b) {
60 int s = 0;
61 if (b[0] > 0)
62 s += b[0];
63 else
64 s += 256 + b[0];
65 s *= 256;
66 if (b[1] > 0)
67 s += b[1];
68 else
69 s += 256 + b[1];
70 char ch = (char) s;
71 return ch;
72 }
73
74 /**
75 * 浮点到字节转换
76 * @param d
77 * @return
78 */
79 public static byte[] doubleToByte(double d) {
80 byte[] b = new byte[8];
81 long l = Double.doubleToLongBits(d);
82 for (int i = 0; i < b.length; i++) {
83 b[i] = new Long(l).byteValue();
84 l = l >> 8;
85
86 }
87 return b;
88 }
89
90 /**
91 * 字节到浮点转换
92 * @param b
93 * @return
94 */
95 public static double byteToDouble(byte[] b) {
96 long l;
97
98 l = b[0];
99 l &= 0xff;
100 l |= ((long) b[1] << 8);
101 l &= 0xffff;
102 l |= ((long) b[2] << 16);
103 l &= 0xffffff;
104 l |= ((long) b[3] << 24);
105 l &= 0xffffffffl;
106 l |= ((long) b[4] << 32);
107 l &= 0xffffffffffl;
108
109 l |= ((long) b[5] << 40);
110 l &= 0xffffffffffffl;
111 l |= ((long) b[6] << 48);
112
113 l |= ((long) b[7] << 56);
114 return Double.longBitsToDouble(l);
115 }
116 }