CRC8反转校验

  最近在做项目遇到一个问题,就是需要对数据进行CRC8校验,多项式是 X7+X6+X5+X2+1,对应的二进制表达是 11100101,但是因为传输反转所以我们这里的多项式二进制表达方式

为 10100111,话不多说,上代码

 

 

  

public class CRC8_76520 {

public static void main(String[] args) {
do_crc76520(BytesAnd16Code.hexStringToBytes("34112233445550"),7);
}



static int ENCPY = 0xE5;/* 11100101 */
/* 定义反转生成多项式*/
static int ENCPY_REV = 0xA7;/* 10100111 */
public static String do_crc76520(byte[] message, int len)
{
int uiMaxBit;
int uiRsb;
int crc_reg;

int uiMesIndex;
int uiLsb;

int i;
int crcreturn = 0x00;

uiMaxBit = len * 8 - 1;
uiRsb = 0;
crc_reg = (message[0] ^ ENCPY_REV);
while (uiRsb < uiMaxBit)
{
if ((crc_reg & 0x01) > 0x00)
{
crc_reg = crc_reg ^ ENCPY_REV;
}
else
{
crc_reg = crc_reg >> 1;
uiMesIndex = uiRsb / 8 + 1;
uiLsb = uiRsb % 8;
if (uiMesIndex < len)
{
if ((message[uiMesIndex] & (0x01 << uiLsb)) > 0x00)
{
crc_reg = crc_reg | 0x80;
}
}
uiRsb++;
}
}
//将crc从发送顺序转变为正常数据表示顺序,即最高位和最低位依次调换
for (i = 0; i < 7; i++)
{
if ((crc_reg & (0x01 << i)) > 0x00)
{
crcreturn = (crcreturn | (0x01 << (7 - i)));
}
}

System.out.println(Integer.toHexString(crcreturn));
return Integer.toHexString(crcreturn);
}


}

 

 

 

   字节数组转16进制字符串类

 

class BytesAnd16Code {

public static void main(String[] args) {
float f = 120.00f;
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}

/**
*
* @param src
* @return
*/
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {

int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}

/**
* Convert hex string to byte[]
* @param hexString the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) { // 0x16
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase(); // 16
int length = hexString.length() / 2; // lenght=1
char[] hexChars = hexString.toCharArray(); //[1,6]
//1,6
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;
}

/**
* Convert char to byte
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}

}

 

转载于:https://www.cnblogs.com/xuzilan/p/8305056.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值