wu
2024-10-15 865e425cdf7395fece0a53a6def75e2c84d6dbf0
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
66
67
68
69
70
71
package com.mes.tools;
 
public class HexConversion {
    /**
     * @param a shuzi
     * @return shuzu
     */
    public static byte[] stringToInt(String a){
        byte[] byt = new byte[a.length()/2];
        for (int i = 0; i < a.length() - 1; i+=2) {
            String output = a.substring(i, i + 2);
            byt[i/2]=(byte)Integer.parseInt(output, 16);
        }
        return byt;
    }
    public static String byteToHexString(int bufSize,byte[] msg){
        String tempHex = "";
        String command = "";
        if (bufSize != -1) {
            for (int i = 0; i < bufSize; i++) {
                tempHex = Integer.toHexString(msg[i] & 0xFF);
                if (tempHex.length() == 1) {
                    tempHex = "0" + tempHex;
                }
                command += tempHex;
            }
        }
        return command;
    }
    public static String intToHex(int number) {
        return Integer.toHexString(number);
    }
    /**
     * 将整数转换为4位16进制,如1转换为0001,10转换为000a
     *
     * @param number
     * @return
     */
    public static String intTo2ByteHex(int number) {
        String numberHex = intToHex(number);
        numberHex = String.format("%4s", numberHex).replace(' ', '0');
        return numberHex;
    }
    /**
     * 将整数转换为2位16进制,如1转换为01,10转换为0a
     *
     * @param
     * @return
     */
    public static String intTo1ByteHex(int number) {
        String numberHex = intToHex(number);
        numberHex = String.format("%2s", numberHex).replace(' ', '0');
        return numberHex;
    }
 
    /**
     * 从byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
     *
     * @param src: byte数组
     * @param offset: 从数组的第offset位开始
     * @return int数值
     */
    public static int bytesToInt(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset+1] & 0xFF)<<8)
                | ((src[offset+2] & 0xFF)<<16)
                | ((src[offset+3] & 0xFF)<<24));
        return value;
    }
}