运算法则:
异或运算
public String XOR_operation(String strHex_X,String strHex_Y){ //16进制字符异或运算
String anotherBinary=Integer.toBinaryString(Integer.valueOf(strHex_X,16)); //16进制字符转二进制字符
String thisBinary=Integer.toBinaryString(Integer.valueOf(strHex_Y,16));
String result = "";
if(anotherBinary.length() != 8){ //判断是否为8位二进制,否则左补零
for (int i = anotherBinary.length(); i <8; i++) {
anotherBinary = "0"+anotherBinary;
}
}
if(thisBinary.length() != 8){
for (int i = thisBinary.length(); i <8; i++) {
thisBinary = "0"+thisBinary;
}
}
for(int i=0;i<anotherBinary.length();i++){ //异或运算 相同取0 不同取1
if(thisBinary.charAt(i)==anotherBinary.charAt(i))
result+="0";
else{
result+="1";
}
}
return Integer.toHexString(Integer.parseInt(result, 2));
}
字节数组异或运算:
public String getXorByte(byte[] bytes){
String temp = "00";
for(int i = 0;i<bytes.length;i++){
temp = XOR_operation(temp,Integer.toHexString(bytes[i] & 0xFF));
}
return temp;
}
字节数组转16进制字符串
public static String bytesToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
}
16进制字符串转byte数组
16进制字符转byte:
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}
16进制字符串转byte数组
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=hexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}
byte[]与int互转
private static int byteArrayToInt(byte[] var0) {
return var0[0] & 255 | (var0[1] & 255) << 8 | (var0[2] & 255) << 16 | (var0[3] & 255) << 24;
}
private static byte[] intToByteArray(int var0) {
return new byte[]{(byte)(var0 & 255), (byte)(var0 >> 8 & 255), (byte)(var0 >> 16 & 255), (byte)(var0 >> 24 & 255)};
}