有懂c++和java的么? 求翻译下c代码

安静的码字猴 2018-03-10 05:16:33
跪求转成java代码 的crc校验

uint16 crc16l(unsigned char *buf,uint16 len)
{
unsigned int crc=0x0000;
unsigned short c,i;
while(len!=0)
{
c=*buf;
for(i=0;i<8;i++)
{
if((crc ^ c) & 1)
crc=(crc>>1)^0xa001;
else
crc>>=1;
c>>=1;
}
len--;
buf++;
}
return crc;

}
...全文
811 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
安静的码字猴 2018-03-21
  • 打赏
  • 举报
回复
@gspUser 你的翻译是正确的,我校验截取错了
gspUser 2018-03-10
  • 打赏
  • 举报
回复
那是你的C函数代码错了,你的C函数的计算结果和工业上常用 Modbus A001 的CRC16计算结果对不上。 用你的说的数据用你的C函数计算出来的CRC校验码,也和你说的校验码不一样, 你给的测试数据与工业用的校验结果也对不上. 用楼上的CRC校验函数得到的校验码也和你给的数据的校验码不一样 unsigned char d[15]={0x7e,0xfe,0x10,0x02,0x21,0x04,0x0b,0x00,0x00,0x00,0x0a,0x24,0x00,0x00,0x00}; printf("0x%04hX\n",exampleOfUseCRC16(d,15));//0x11FB printf("0x%04hX\n",crc16l(d,15));//0x61C9 不知道你的CRC是用什么样的表达式, 也可能是你的数据需要的校验起始字节不是从第一个字节开始的 有没有协议
赵4老师 2018-03-10
  • 打赏
  • 举报
回复
仅供参考:
/***** crc16.c *****/
#include <stdio.h>

#define CRC16_DNP   0x3D65u     // DNP, IEC 870, M-BUS, wM-BUS, ...
#define CRC16_CCITT 0x1021u     // X.25, V.41, HDLC FCS, Bluetooth, ...

//Other polynoms not tested
#define CRC16_IBM   0x8005u     // ModBus, USB, Bisync, CRC-16, CRC-16-ANSI, ...
#define CRC16_T10_DIF   0x8BB7u     // SCSI DIF
#define CRC16_DECT  0x0589u     // Cordeless Telephones
#define CRC16_ARINC 0xA02Bu     // ACARS Aplications

#define POLYNOM     CRC16_DNP   // Define the used polynom from one of the aboves

// Calculates the new crc16 with the newByte. Variable crcValue is the actual or initial value (0).
unsigned short crc16(unsigned short crcValue, unsigned char newByte) {
    int i;

    for (i = 0; i < 8; i++) {
        if (((crcValue & 0x8000u) >> 8) ^ (newByte & 0x80u)){
            crcValue = (crcValue << 1)  ^ POLYNOM;
        } else {
            crcValue = (crcValue << 1);
        }
        newByte <<= 1;
    }
    return crcValue;
}

unsigned short exampleOfUseCRC16(unsigned char *Data, int len){

    unsigned short crc;
    int aux = 0;

    crc = 0x0000u; //Initialization of crc to 0x0000 for DNP
    //crc = 0xFFFFu; //Initialization of crc to 0xFFFF for CCITT

    while (aux < len){
        crc = crc16(crc,Data[aux]);
        aux++;
    }

    return (~crc); //The crc value for DNP it is obtained by NOT operation

    //return crc; //The crc value for CCITT
}

int main() {
    unsigned char d[10]={0,1,2,3,4,5,6,7,8,9};

    printf("0x%04hX\n",exampleOfUseCRC16(d,10));//0x1078
    return 0;
}
安静的码字猴 2018-03-10
  • 打赏
  • 举报
回复
7efe100221040b0000000a24000000 ca05 05 crc校验和应该是 ca05,但是算出来的不对 啊 能帮忙看下么
gspUser 2018-03-10
  • 打赏
  • 举报
回复
java和C++的代码很相似,小小改动就可以了,运行结果和C++的是一样的 public static int CRC16(byte[] buf,int len) { int crc=0x0000; short c,i; int mindex=0; while(len!=0) { c=buf[mindex++]; for(i=0;i<8;i++) { if(((crc ^ c) & 1)>0) crc=(crc>>1)^0xa001; else crc>>=1; c>>=1; } len--; } return crc; }

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧