Java byte、int、String之间相互转化

1、byte与int转换

//Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值

public static byte intToByte(int x) {   
return (byte) x;   
}   
public static int byteToInt(byte b) {   
return b & 0xFF;   
} 


#byte[]与int转换 
public static int byteArrayToInt(byte[] b) {   
return   b[3] & 0xFF |   
            (b[2] & 0xFF) << 8 |   
            (b[1] & 0xFF) << 16 |   
            (b[0] & 0xFF) << 24;   
}   
public static byte[] intToByteArray(int a) {   
return new byte[] {   
        (byte) ((a >> 24) & 0xFF),   
        (byte) ((a >> 16) & 0xFF),      
        (byte) ((a >> 8) & 0xFF),      
        (byte) (a & 0xFF)   
    };   
} 

2、byte[]转String/String 转 byte[]

//字节数组转为字符串 
    static public String ByteArrayToString(byte[] bytes){
        if(bytes == null){
            return  null;
        }
        String str = new String(bytes);
        return str;
    }
------------------------------------------------------------------------
//String 转 byte[]
public static byte[] strToByteArray(String str) {
    if (str == null) {
        return null;
    }
    byte[] byteArray = str.getBytes();
    return byteArray;
}

3、字节数组转hex字符串/hexString转byte[]

static public String ByteArrToHexString(byte[] inBytArr)
    {
        StringBuilder strBuilder=new StringBuilder();
        int j=inBytArr.length;
        for (int i = 0; i < j; i++)
        {
            strBuilder.append(Byte2Hex(inBytArr[i]));
            strBuilder.append(" ");
        }
        return strBuilder.toString();
    }
----------------------------------------------------------------------------------------------
public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容