Java大小端数据互转

Java大小端数据互转

/**
 * @author Created by wenhui
 * @description
 * Java大小端数据互转
 * 数据是以大端模式存储的,而机器是小端模式,必须进行转换,否则使用时会出问题
 * @date 2019/12/19
 */
public class String2Bytes {

    public static void main(String[] args) {
        String str = "060582CF0001CADE";
        byte[] bt = string2Bytes(str);
        System.out.println(Long.toHexString(getLong(bt, true)));
    }

    public static byte[] string2Bytes(String str) {
        if (str == null || str.equals("")) {
            return null;
        }
        str = str.toUpperCase();
        int length = str.length() / 2;
        char[] strChar = str.toCharArray();
        byte[] bt = new byte[length];
        for (int i = 0; i < length; i++) {
            int index = i * 2;
            bt[i] = (byte) (char2Byte(strChar[index]) << 4 | char2Byte(strChar[index + 1]));
        }
        return bt;
    }

    private static byte char2Byte(char ch) {
        return (byte) "0123456789ABCDEF".indexOf(ch);
    }

    public final static long getLong(byte[] bt, boolean isAsc) {
        //BIG_ENDIAN
        if (bt == null) {
            throw new IllegalArgumentException("byte array is null.");
        }
        if (bt.length > 8) {
            throw new IllegalArgumentException("byte array size more than 8.");
        }
        long result = 0;
        if (isAsc)
            for (int i = bt.length - 1; i >= 0; i--) {
                result <<= 8;
                result |= (bt[i] & 0x00000000000000ff);
            }
        else
            for (int i = 0; i < bt.length; i++) {
                result <<= 8;
                result |= (bt[i] & 0x00000000000000ff);
            }
        return result;
    }

}

输出结果:
Java大小端数据互转_第1张图片

你可能感兴趣的:(Java)