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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值