‘liusuyi’
2023-07-03 fbb9b4374821b43d0b85aa569977415fd8d77cd9
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
72
73
74
75
76
77
78
79
80
81
82
package com.ard.utils;
 
import javax.xml.bind.DatatypeConverter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
/**
 * @Description: 字节工具类
 * @ClassName: byteUtils
 * @Author: 刘苏义
 * @Date: 2023年07月03日15:18
 * @Version: 1.0
 **/
public class ByteUtils {
    /**
     * Byte字节转Hex
     * @param b 字节
     * @return Hex
     */
    public static String byteToHex(byte b)
    {
        String hexString = Integer.toHexString(b & 0xFF);
        //由于十六进制是由0~9、A~F来表示1~16,所以如果Byte转换成Hex后如果是<16,就会是一个字符(比如A=10),通常是使用两个字符来表示16进制位的,
        //假如一个字符的话,遇到字符串11,这到底是1个字节,还是1和1两个字节,容易混淆,如果是补0,那么1和1补充后就是0101,11就表示纯粹的11
        if (hexString.length() < 2)
        {
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase();
    }
    /**
     * byte数组转float
     */
    public static float bytesToFloat(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        return buffer.getFloat();
    }
    /**
     * byte数组转整型
     */
    public static int bytesToDecimal(byte[] byteArray) {
        int decimalValue = 0;
 
        for (int i = 0; i < byteArray.length; i++) {
            decimalValue = (decimalValue << 8) | (byteArray[i] & 0xFF);
        }
 
        return decimalValue;
    }
 
    /**
     * byte数组转Double
     */
    public static double bytesToDouble(byte[] byteArray) {
        long longBits = 0;
 
        // 根据字节数组的长度和字节顺序,将字节数组转换为长整型
        for (int i = 0; i < byteArray.length; i++) {
            longBits |= (long) (byteArray[i] & 0xFF) << (8 * (byteArray.length - 1 - i));
        }
 
        // 使用Double.longBitsToDouble方法将长整型转换为Double类型
        return Double.longBitsToDouble(longBits);
    }
 
    /**
     * 大端转小端
     */
    public static byte[] toLittleEndian(byte[] bigEndianBytes) {
        byte[] littleEndianBytes = new byte[bigEndianBytes.length];
 
        for (int i = 0; i < bigEndianBytes.length; i++) {
            int j = bigEndianBytes.length - i - 1;
            littleEndianBytes[i] = bigEndianBytes[j];
        }
 
        return littleEndianBytes;
    }
 
}