Java對十六進制文件讀取


注:當前文件中的數據順序:低位在前、高位在后

Java對十六進制文件的讀取,尤其是使用readInt()和readDouble()方法時必須要對數據進行轉換,這樣才可以避免讀到的數據出錯。

我們先提供一個數據轉換的類,這樣可以便於后面的數據轉換:

  類名:ByteToOther

     方法:

    public int intFromByte(byte[] temp){
        int value = 0;
//      value = (((temp[0] & 0xff) << 24) | ((temp[1] & 0xff) << 16) | ((temp[2] & 0xff) << 8) | (temp[3] & 0xff));
        value = ((temp[0] & 0xff) | ((temp[1] & 0xff) << 8) | ((temp[2] & 0xff) << 16) | ((temp[3] & 0xff) << 24));
        return value;
    }


    public double doubleFromByte(byte[] temp){
        byte tem = 0;
        for(int i = 0; i < (temp.length + 1)/2; i ++){
            tem = temp[i];
            temp[i] = temp[temp.length - 1 - i];
            temp[temp.length - 1 - i] = tem;
        }
        long val = (((long)(temp[0] & 0xff) << 56) | ((long)(temp[1] & 0xff) << 48) | ((long)(temp[2] & 0xff) << 40) | ((long)(temp[3] & 0xff) << 32) | ((long)(temp[4] & 0xff) << 24) | ((long)(temp[5] & 0xff) << 16) | ((long)(temp[6] & 0xff) << 8) | (long)(temp[7] & 0xff));
        double value = Double.longBitsToDouble(val);
        return value;

    }

 

讀取類:FileReader

    public List<Point2D.Double> readFileCor(String path){
        List<Point2D.Double> points = new ArrayList<Point2D.Double>();
        File file = new File(path);
        
        try {
            FileInputStream in = new FileInputStream(file);
            ByteToOther tTO = new ByteToOther();
            for(int i = 0; i < file.length()/16; i ++){
                Point2D.Double point = new Point2D.Double();
                byte[] px = new byte[8];
                byte[] py = new byte[8];
                in.read(px);
                in.read(py);
                point.x = tTO.doubleFromByte(px);
                point.y = tTO.doubleFromByte(py);
                points.add(point);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return points;
    }

注:如果文件中的數據順序:高位在前、低位在后時,ByteToOther類應做如下處理

   public int intFromByte(byte[] temp){
        int value = 0;
        value = (((temp[0] & 0xff) << 24) | ((temp[1] & 0xff) << 16) | ((temp[2] & 0xff) << 8) | (temp[3] & 0xff));
        return value;
    }


    public double doubleFromByte(byte[] temp){
        byte tem = 0;
        long val = (((long)(temp[0] & 0xff) << 56) | ((long)(temp[1] & 0xff) << 48) | ((long)(temp[2] & 0xff) << 40) | ((long)(temp[3] & 0xff) << 32) | ((long)(temp[4] & 0xff) << 24) | ((long)(temp[5] & 0xff) << 16) | ((long)(temp[6] & 0xff) << 8) | (long)(temp[7] & 0xff));
        double value = Double.longBitsToDouble(val);
        return value;

   }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM