java 异或运算操作16位进制
package cc.javar.util;
/***
* 异或效验
* @author chenji
***/
public class ByteCheck {
public static runXor(String[] args) {
String zhi16="5A A5 10 10 11 00 66 66 10 10 10 00 10 19 01 00 04 03 02 00 96 65 68 6C 00 5A A5 10 10 11 00 66 66 10 10 10 00 10 19 01 00 04 03 02 00 96 65 68";
String code = checkcode(zhi16.trim);
System.out.println("code:" + code);
}
public static String checkcode(String para) {
int length = para.length() / 2;
String[] dateArr = new String[length];
for (int i = 0; i < length; i++) {
dateArr[i] = para.substring(i * 2, i * 2 + 2);
}
String code = "00";
for (int i = 0; i < dateArr.length; i++) {
code = xor(code, dateArr[i]);
}
if(code.length()<2){
code = "0"+code;
}
return code;
}
private static String xor(String strHex_X, String strHex_Y) {
// 将x、y转成二进制形式
String anotherBinary = Integer.toBinaryString(Integer.valueOf(strHex_X,
16));
String thisBinary = Integer.toBinaryString(Integer
.valueOf(strHex_Y, 16));
String result = "";
// 判断是否为8位二进制,否则左补零
if (anotherBinary.length() != 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";
}
}
System.out.println(result);
return Integer.toHexString(Integer.parseInt(result, 2));
}
}
最后更新于 2022-06-25 22:15:12 并被添加「」标签,已有 1527 位网友阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处
此处评论已关闭