whycrzg
2021-03-11 6e3aac63644b72036f8aa9348c50488e0e121723
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package test.java.org.pzone.crypto;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
 
public class ComFn {
    public static String bytesToHexString(byte[] src, int len){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || len <= 0) {
            return null;
        }
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    
    public static byte[] hexStr2Byte(String hex) {
        ByteBuffer bf = ByteBuffer.allocate(hex.length() / 3);
        for (int i = 0; i<hex.length(); i++) {
            String hexStr = hex.charAt(i++) + "";
            hexStr += hex.charAt(i++);
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr.trim(), 16);
            bf.put(b);
        }
        return bf.array();
    }
    
    /**
     * 把一个文件转化为byte字节数组。
     *
     * @return
     */
    public byte[] fileConvertToByteArray(String src_file) {
        byte[] data = null;
 
        try {
            FileInputStream fis = new FileInputStream(new File(src_file));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
 
            data = baos.toByteArray();
 
            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return data;
    }
}