NetworkingCar/src/main/java/com/muyu/utils/CalculateCheckDigit.java

45 lines
1.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.muyu.utils;
/**
* 校验位计算
*/
public class CalculateCheckDigit {
/**
* 不去空格
* @param sHex
* @return
*/
public static String makeCheck(String sHex){
return makeCheckSum(sHex.replace(" ", ""));
}
/**
* 计算校验位 ,返回十六进制校验位
* */
private static String makeCheckSum(String data) {
int dSum = 0;
int length = data.length();
int index = 0;
// 遍历十六进制,并计算总和
while (index < length) {
// 截取2位字符
String s = data.substring(index, index + 2);
// 十六进制转成十进制 , 并计算十进制的总和
dSum += Integer.parseInt(s, 16);
index = index + 2;
}
// 用256取余十六进制最大是FFFF的十进制是255
int mod = dSum % 256;
// 余数转成十六进制
String checkSumHex = Integer.toHexString(mod);
length = checkSumHex.length();
if (length < 2) {
// 校验位不足两位的在前面补0
checkSumHex = "0" + checkSumHex;
}
return checkSumHex;
}
}