java下 dec hex byte数组转换


十进制字符串转十六进制:

    public static String stringToHexString(String strPart) {
        String hexString = "";
        for (int i = 0; i < strPart.length(); i++) {
            int ch = (int) strPart.charAt(i);
            String strHex = Integer.toHexString(ch);
            hexString = hexString + strHex;
        }
        return hexString;
    }


十六进制字符串转byte数组:

public static byte[] hexToBytes(String s) {
s = s.toUpperCase();
int len = s.length() / 2;
int ii = 0;
byte[] bs = new byte[len];
char c;
int h;
for (int i = 0; i < len; i++) {
c = s.charAt(ii++);
if (c <= '9') {
h = c - '0';
} else {
h = c - 'A' + 10;
}
h <<= 4;
c = s.charAt(ii++);
if (c <= '9') {
h |= c - '0';
} else {
h |= c - 'A' + 10;
}
bs[i] = (byte) h;
}
return bs;
}


byte数组转十进制字符串:


public static String bytes2string(byte[] bs) {
char[] cs = new char[bs.length];
for (int p = 0; p < bs.length; p++) {
cs[p] = (char) (bs[p] & 0xFF);
}
return new String(cs);
}



byte数组转十六进制字符串:


    public static final 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();  
    }



当需要对两个字符串异或操作的时候,现将其转换成byte数组,然后进行异或操作:


    public byte[] mimajiami(byte[] a , byte[] b){
    byte[] re = new byte[a.length];
   
    for(int i =0;i<a.length;i++){
    re[i]=(byte) (a[i]^b[i]);
    }
   
    return re;
   
    }




猜你喜欢

转载自blog.csdn.net/mashengjun1989/article/details/75043722
hex
今日推荐