Data type conversion

Convert byte array to hexadecimal

// Read data from binary file into input stream, read byte from input stream, convert byte to hexadecimal
public void readFile() {
        // Specify a binary file
        String fileName = "gpb_20101210.dat";
        File file = new File(fileName);
        if (!file.exists()) {
                out.println("Can not obtain sepcified file.");
                return;
        }
        try {
                // Read binary file into input tream
                FileInputStream in = new FileInputStream(fileName);
                int c;
                int i=0;
                // Loop to read byte from input stream
                while((c=in.read())!=-1)     
                {
                        if(i==16) {
                                out.println();
                                i=0;
                        }
                        // Convert byte to hexadecimal
                        String hex = Integer.toHexString(c & 0xFF);
                        if (hex.length() == 1) {
                                hex = '0' + hex;
                        }
                        // Print hexadecimal followed by a space
                        out.print(hex.toUpperCase() + " ");     
                }
        } catch (IOException e) {
                e.printStackTrace();
        }catch (FileNotFoundException e) {
                out.println("Read file failure.");
                e.printStackTrace();
        }
}

Array of 4 bytes to int

/**
* Converts a high bytes array that length is 4 to a integer digital
* @param byteArray: will be converted the bytes array that length is 4
* @return converted: integer digital
*/
public static int hBytesToInt(byte[] byteArray) {
        int s = 0;
        for (int i = 0; i < 3; i++) {
                if (byteArray[i] >= 0) {
                        s = s + byteArray[i];
                } else {
                        s = s + 256 + byteArray[i];
                }
                s = s * 256;
        }
        if (byteArray[3] >= 0) {
                s = s + byteArray[3];
        } else {
                s = s + 256 + byteArray[3];
        }
        return s;
}

int to byte array

/**
* Converts a integer digital to 4 bytes array.
*
* @param a
* @return
*/
public static byte[] intToByte(int a) {
        byte[] bArray = new byte[4];
        for (int i = bArray.length; i > 0; i--) {
                bArray[i - 1] = new Integer(a & 0XFF).byteValue();
                a >>= 8;
        }
        return bArray;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章