我收到了C中的一段代码,它计算字节数组的CRC8 8值。我需要把它翻译成Java。
在这里,C代码:
CRC_POLYNOM = 0x9c;
CRC_PRESET = 0xFF;
unsigned int CRC = CRC_PRESET;
for (i = 0; i < Len; i++)
{
crc ^= FRAME[i];
for (j = 0; j < 8; j++)
{
if (crc & 0x01)
crc = (crc >> 1) ^ CRC_POLYNOM;
else
crc = (crc >> 1);
}
}我所做的是用Java实现的。
public static long calculateCRC8(byte[] b, int len) {
long crc = CRC_PRESET;
for (int i = 0; i < len; i++) {
crc ^= b[i];
for (int j = 0; j < 8; j++) {
if ((crc & 0x01) == 0)
crc = (crc >> 1) ^ CRC_POLYNOM;
else
crc = crc >> 1;
}
}
return crc;
}对于字节数组示例:
byte[] b = new byte[] {1, 56, -23, 3, 0, 19, 0, 0, 2, 0, 3, 13, 8, -34, 7, 9, 42, 18, 26, -5, 54, 11, -94, -46, -128, 4, 48, 52, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1, -32, -80, 0, 98, -5, 71, 0, 64, 0, 0, 0, 0, -116, 1, 104, 2};C代码返回29,我的Java代码返回44。我做错什么了?
我认为这是因为Java的只有签名的数据类型,那么我如何解决这个问题呢?
发布于 2014-08-13 11:26:54
你的"^“实际上已经像箭头一样指向错误所在的部分。
相当于
if (crc & 0x01)在Java中应该是(因为java需要if中的布尔表达式)
if ((crc & 0x01) != 0)或
if ((crc & 0x01) == 0x01)发布于 2014-11-18 16:14:27
我为您的问题创建了一个完整的/独立的C程序:
#include <stdio.h>
#define CRC_POLYNOM 0x9c
#define CRC_PRESET 0xFF
int main() {
unsigned int crc = CRC_PRESET;
unsigned char FRAME[] = {1, 56, -23, 3, 0, 19, 0, 0, 2, 0, 3, 13, 8, -34, 7, 9, 42, 18, 26, -5, 54, 11, -94, -46, -128, 4, 48, 52, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1, -32, -80, 0, 98, -5, 71, 0, 64, 0, 0, 0, 0, -116, 1, 104, 2};
for(int i = 0; i < sizeof(FRAME); i++) {
crc ^= FRAME[i];
for(int j = 0; j < 8; j++) {
if(crc & 0x01) {
crc = (crc >> 1) ^ CRC_POLYNOM;
} else {
crc = (crc >> 1);
}
}
}
printf("%u\n", crc);
return 0;
}这里,在https://www.mtsystems.com上自动创建等效的Java代码
package demo;
public class DemoTranslation {
public final static int CRC_POLYNOM = 0x9c;
public final static int CRC_PRESET = 0xFF;
public static void main(String[] args) {
int crc_U = CRC_PRESET;
byte[] frame_U = {1, 56, -23, 3, 0, 19, 0, 0, 2, 0, 3, 13, 8, -34, 7, 9, 42, 18, 26, -5, 54, 11, -94, -46, -128, 4, 48, 52, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1, -32, -80, 0, 98, -5, 71, 0, 64, 0, 0, 0, 0, -116, 1, 104, 2};
for(int i = 0; i < frame_U.length; i++) {
crc_U ^= Byte.toUnsignedInt(frame_U[i]);
for(int j = 0; j < 8; j++) {
if((crc_U & 0x01) != 0) {
crc_U = (crc_U >>> 1) ^ CRC_POLYNOM;
} else {
crc_U = (crc_U >>> 1);
}
}
}
System.out.println(Integer.toUnsignedString(crc_U));
}
}发布于 2022-02-21 23:13:38
有了公认的答案,我无法得到与在线CRC8计算器(如js.html )匹配的校验和。
因此,我将https://github.com/RobTillaart/CRC/blob/master/CRC8.cpp从C转换为Java,并使用各种初始值和多项式成功地进行了测试:
final byte[] data = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}; // sample data
final byte INIT_VAL = (byte) 0x00;
final byte POLY = 0x07;
int _crc = INIT_VAL;
for (int j = 0; j < data.length; j++) {
int value = data[j];
_crc = _crc ^ value;
for (int i = 8; i > 0; i--) {
if ((_crc & (1 << 7)) > 0) {
_crc <<= 1;
_crc ^= POLY;
} else {
_crc <<= 1;
}
}
}
result = (_crc & 0xff);https://stackoverflow.com/questions/25284556
复制相似问题