Java解析字节文件

1、将字节文件读取为字节数组

byte[] data= Files.readAllBytes(Paths.get(path));

2、按照定义的数据结构解析字节数组(例)


 public DataIndex readFsIndexData(byte[] data, int pIndex) throws IOException {

        DataIndex dataIndex = new DataIndex();
        ByteBuffer dataFieldBf = ByteBuffer.wrap(data);

        //跳过表头
        byte[] spare = new byte[pIndex];
        dataFieldBf.get(spare);

        //数据地址
        byte[] dataAddress = new byte[4];
        dataFieldBf.get(dataAddress);
        dataIndex.setDataAddress(byteUtils.fourByte2Int(dataAddress));

        //行数
        byte[] rowNumber = new byte[2];
        dataFieldBf.get(rowNumber);
        dataIndex.setRowNumber(byteUtils.twoByte2IntBig(rowNumber));

        //列数
        byte[] columnNumber = new byte[2];
        dataFieldBf.get(columnNumber);
        dataIndex.setColumnNumber(byteUtils.twoByte2IntBig(columnNumber));

        return dataIndex;
    }

3、ByteUtils.Java

可能会涉及到操作字节的方法

 @Slf4j
@Component
public class ByteUtils {

    //base64字符串转byte[]
    public byte[] base64String2ByteFun(String base64Str) {
        return Base64.decodeBase64(base64Str);
    }

    //byte[]转base64
    public String byte2Base64StringFun(byte[] b) {
        return Base64.encodeBase64String(b);
    }

    /**
     * 对象转数组
     *
     * @param obj
     * @return
     */
    public byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }


    /**
     * Hex转byte[],两种情况,Hex长度为奇数最后一个字符会被舍去
     */
    public byte[] hexTobytes(String hex) {
        if (hex.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hex.length() / 2];
            int j = 0;
            for (int i = 0; i < hex.length(); i += 2) {
                result[j++] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
            }
            return result;
        }
    }

    /**
     * @Description: byte转Stringd
     * 
     */
    public final static String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * // 转化十六进制编码为字符串 utf-8
     * @param s
     * @return
     */
    public static String toStringHex2(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
               byte a =  (byte) (0xff & Integer.parseInt(s.substring(
                        i * 2, i * 2 + 2), 16));
                baKeyword[i]=a;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            int length = 0;
            for (int i = 0; i < baKeyword.length; ++i) {
                if (baKeyword[i] == 0) {
                    length = i;
                    break;
                }
            }
            s = new String(baKeyword,  0, length,"utf-8");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 判断是否为数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        for (int i = str.length();--i>=0;){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }


    /**
     * // 转化十六进制编码为字符串 GBK
     * @param s
     * @return
     */
    public static String toStringHex2GBK(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
                        i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            int length = 0;
            for (int i = 0; i < baKeyword.length; ++i) {
                if (baKeyword[i] == 0) {
                    length = i;
                    break;
                }
            }
            s = new String(baKeyword, 0, length,"GBK");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }



    public String bytesToStr_Little(byte[] bytes) {
        return bytesToHexString(smallHexBytesToBigHexBytes(bytes));
    }

    /**
     * CRC16-XMODEM算法(四字节)
     *
     * @param bytes
     * @return
     */
    public static int crc16_ccitt_xmodem(byte[] bytes) {
        int crc = 0x0000; // initial value
        int polynomial = 0x1021; // poly value
        for (int index = 0; index < bytes.length; index++) {
            byte b = bytes[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        crc &= 0xffff;
        return crc;
    }

    static final char[] crc_tb = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce,
            0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
            0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653,
            0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5,
            0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7,
            0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5,
            0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13,
            0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d,
            0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f,
            0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
            0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3,
            0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865,
            0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37,
            0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45,
            0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93,
            0x3eb2, 0x0ed1, 0x1ef0};

    private static int Crc(byte[] Source) {
        int len = Source.length;
        char crc;
        byte da;
        crc = 0x0;
        int i = 0;
        while (len-- != 0) {
            da = (byte) (crc / 256);
            crc <<= 8;
            int num = da ^ Source[i];
            if (num < 0) num += 256;
            crc ^= crc_tb[num];
            ++i;
        }
        return (int) crc;
    }

    public byte[] getCRC2(byte[] bytes) {
        return int2byte_Little(Crc(bytes), 2);

    }

    public byte[] int2byte(int l, int byteLength) {
        byte[] bytes = new byte[byteLength];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) ((l >> (8 * (bytes.length - 1 - i))) & 0xff);
        }
        return bytes;
    }

    /**
     * 小端数组转大端数组
     *
     * @param smallHexBytes
     * @return
     */
    public byte[] smallHexBytesToBigHexBytes(byte[] smallHexBytes) {
        byte[] bigHexBytes = new byte[smallHexBytes.length];
        int i = 0;
        for (int k = smallHexBytes.length - 1; k >= 0; k--) {
            byte smallHexByte = smallHexBytes[k];
            bigHexBytes[i] = smallHexByte;
            i++;
        }
        return bigHexBytes;
    }

    /*
     * 字符串转换为十六进制的byte数组
     */
    public byte[] hexStringToByte(String hex) {
        hex = hex.replace("0x","");
        if (hex.length() == 1){
            hex = "0" + hex;
        }
        if (hex.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hex.length() / 2];
            int j = 0;
            for (int i = 0; i < hex.length(); i += 2) {
                result[j++] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
            }
            return result;
        }
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }


    /**
     * @Description: byte转double
     */
    public double byte2double(byte[] b) {
        long m;
        m = b[0];
        m &= 0xff;
        m |= ((long) b[1] << 8);
        m &= 0xffff;
        m |= ((long) b[2] << 16);
        m &= 0xffffff;
        m |= ((long) b[3] << 24);
        m &= 0xffffffffl;
        m |= ((long) b[4] << 32);
        m &= 0xffffffffffl;
        m |= ((long) b[5] << 40);
        m &= 0xffffffffffffl;
        m |= ((long) b[6] << 48);
        m &= 0xffffffffffffffl;
        m |= ((long) b[7] << 56);
        return Double.longBitsToDouble(m);
    }

    /**
     * byte转换 成int
     *
     * @param data   : 转换数据
     * @param offset :
     * @param length :
     * @return
     */
    public int byte2Int(byte[] data, int offset, int length) {
        int x = 0;

        for (int i = 0; i < length; i++) {
            x = x << 8;
            x += data[offset + i] & 0xff;
        }
        return x;
    }

    /**
     * @Description: 小端模式BYTE转int
     *
     */
    public Integer byte2int_Little(byte[] bytes) {
        int x = 0;

        for (int i = 0; i < bytes.length; i++) {
            x = x << 8;
            x += bytes[bytes.length - 1 - i] & 0xff;
        }
        return x;
    }

    /**
     * @Description: 小端模式BYTE转long
     *
     */
    public Long byte2long_Little(byte[] bytes) {
        long x = 0;

        for (int i = 0; i < bytes.length; i++) {
            x = x << 8;
            x += bytes[bytes.length - 1 - i] & 0xff;
        }
        return x;
    }

    public static byte[] str2Bcd(String asc) {
        int len = asc.length();
        int mod = len % 2;

        if (mod != 0) {
            asc = "0" + asc;
            len = asc.length();
        }

        byte abt[] = new byte[len];
        if (len >= 2) {
            len = len / 2;
        }

        byte bbt[] = new byte[len];
        abt = asc.getBytes();
        int j, k;

        for (int p = 0; p < asc.length() / 2; p++) {
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
                j = abt[2 * p] - '0';
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
                j = abt[2 * p] - 'a' + 0x0a;
            } else {
                j = abt[2 * p] - 'A' + 0x0a;
            }

            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
                k = abt[2 * p + 1] - '0';
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
                k = abt[2 * p + 1] - 'a' + 0x0a;
            } else {
                k = abt[2 * p + 1] - 'A' + 0x0a;
            }

            int a = (j << 4) + k;
            byte b = (byte) a;
            bbt[p] = b;
        }
        return bbt;
    }

    /**
     * 合并多个数组
     *
     * @param values 多个数组
     * @return
     */
    public byte[] byteMergerAll(byte[]... values) {
        int length_byte = 0;
        for (int i = 0; i < values.length; i++) {
            length_byte += values[i].length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }

    public static float getFloat(byte[] data, int offset, int length) {
        int x = 0;
        for (int i = 0; i < length; i++) {
            x = x << 8;
            x += data[offset + i] & 0xff;
        }
        return Float.intBitsToFloat(x);
    }

    public static float byte2float(byte[] b, int index) {
        int l;
        l = b[index + 0];
        l &= 0xff;
        l |= ((long) b[index + 1] << 8);
        l &= 0xffff;
        l |= ((long) b[index + 2] << 16);
        l &= 0xffffff;
        l |= ((long) b[index + 3] << 24);
        return Float.intBitsToFloat(l);
    }

    /*
     *小端端模式的 int转十六进制byte
     */
    public byte[] int2byte_Little(int l, int byteLength) {
        byte[] bytes = new byte[byteLength];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) ((l >> (8 * i)) & 0xff);
        }
        return bytes;
    }


    /*
     *小端端模式的 Long转十六进制byte
     */
    public byte[] long2byte_Little(long l, int byteLength) {
        byte[] bytes = new byte[byteLength];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) ((l >> (8 * i)) & 0xff);
        }
        return bytes;
    }

    public float byte2float2(byte[] b) {
        float aFloat = ByteBuffer.wrap(b).getFloat();
        return aFloat;
    }


    /**
     * Byte转Bit
     */
    public static String byteToBit(byte b) {
        return "" + (byte) ((b >> 7) & 0x1) +
                (byte) ((b >> 6) & 0x1) +
                (byte) ((b >> 5) & 0x1) +
                (byte) ((b >> 4) & 0x1) +
                (byte) ((b >> 3) & 0x1) +
                (byte) ((b >> 2) & 0x1) +
                (byte) ((b >> 1) & 0x1) +
                (byte) ((b) & 0x1);
    }

    public String byteArrToBitStr(byte[] bytes) {
        if(bytes == null || bytes.length == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(byteToBit(b));
        }
        return sb.toString();
    }

    /**
     * Byte转Bit集合
     */
    public List<String> byteToBitList(byte b) {
        List<String> bitList = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            bitList.add((byte) ((b >> i) & 0x1) + "");
        }
        return bitList;
    }

    /**
     * Byte转Bit集合
     */
    public void getSubpackageInfo(String reportedName, List<AtsDataPacket> atsDataPacketList) {
        if (atsDataPacketList != null && atsDataPacketList.size() > 0){
            for (AtsDataPacket atsDataPacket : atsDataPacketList) {
                log.debug("{}数据包总数:{},当前包id{},当前包发送序号{},存入时间{}", reportedName, atsDataPacket.getPacketCount(), atsDataPacket.getCurrentPacketID(), atsDataPacket.getSendSequence(), atsDataPacket.getCurrentTimeMillis());
                log.debug("{}原始分包数据:{}", reportedName, this.bytesToHexString(atsDataPacket.getDataBytes()));
            }
        }
    }

    /**
     * byte转换 成int
     */
    public static int byte2Int(byte[] data, int length) {
        int x = 0;

        for (int i = 0; i < length; i++) {
            x = x << 8;
            x += data[i] & 0xff;
        }
        return x;
    }

    /**
     * byte转换 成有符号int
     */
    public static int byte2SignedInt(byte[] bytes, int length){
        if(length==1){
            return bytes[0]&0xff;
        }else if(length==2){
            int int1=bytes[1]&0xff;
            int int2=(bytes[0]&0xff)<<8;
            return int1|int2;
        }else if(length==3){
            int int1=bytes[2]&0xff;
            int int2=(bytes[1]&0xff)<<8;
            int int3=(bytes[0]&0xff)<<16;
            return int1|int2|int3;
        }else if(length==4){
            int int1=bytes[3]&0xff;
            int int2=(bytes[2]&0xff)<<8;
            int int3=(bytes[1]&0xff)<<16;
            int int4=(bytes[0]&0xff)<<24;
            return int1|int2|int3|int4;
        }
        return -1;

    }

    /**
     * byte获取指定bit偏移值
     */
    public static int byteGetBit(byte b, int bitAnOffset) {
        List<Integer> bitList = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            bitList.add(Integer.parseInt((byte) ((b >> i) & 0x1) + ""));
        }
        return bitList.get(bitAnOffset);
    }

    /**
     * 大端模式byte转int 2byte
     * @param b 字节数组
     * @return int
     */
    public int twoByte2IntBig(byte[] b) {
        int intValue = 0;
        byte[] t_byte = {0, 0};

        if (b.length <= 2) {
            System.arraycopy(b, 0, t_byte, 2 - b.length, b.length);
        }
        for (int i = 0; i < t_byte.length; i++) {
            intValue += (t_byte[i] & 0xFF) << (8 * (1 - i));
        }
        return intValue;
    }

    /**
     * 大端模式byte转int 4byte
     * @param b 字节数组
     * @return int
     */
    public int fourByte2Int(byte[] b) {
        int intValue = 0;
        byte[] t_byte = {0, 0, 0, 0};

        if (b.length <= 4) {
            System.arraycopy(b, 0, t_byte, 4 - b.length, b.length);
        }
        for (int i = 0; i < t_byte.length; i++) {
            intValue += (t_byte[i] & 0xFF) << (8 * (3-i));
        }
        return intValue;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值