gpt4 book ai didi

c++ - 在 C++ 中使用字符指针从字符数组中读取字节

转载 作者:行者123 更新时间:2023-11-28 07:02:11 25 4
gpt4 key购买 nike

我在 Arduino Uno 上使用代码。我一直试图让这段代码做的是遍历我的字节数组,称为“样本”,并计算一个十六进制的 CRC-32 值。我已经确认此代码成功计算了 CRC_32,但仅当将“sample”视为 ASCII 字符串时。要更清楚地理解我的意思,请查看: enter link description here

在该网页上,如果您将“sample”作为一个连续的字符串(即 82818030.....),而选择 ASCII 对话框时,您将得到一个特定的答案,这与 HEX 对话框时不同被选中。我一直在尝试实现该结果(即 0x430F8AB5)。如果有任何帮助,我将不胜感激。

代码如下:

#include "Arduino.h"
//#include "lib_crc.h"



unsigned char sample[90] = {
0x82,0x81, 0x80, 0x30, 0, 0, 0, 0, 0x21, 0x46, 0x01, 0x1D, 0, 0, 0, 0, 0x3F, 0x01, 0x22, 0x22, 0, 0x06, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0x80, 0x0E, 0, 0, 0, 0, 0xFA, 0, 0, 0x27, 0x85, 0x07, 0x0F, 0x4C, 0x82, 0x80, 0, 0, 0, 0x05, 0x01, 0xC1, 0x13, 0x1D, 0, 0, 0, 0, 0x3F,0x01, 0x22, 0, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0xFA, 0, 0, 0x27};
//unsigned char sample[] = "828180300000214611D00003F1222206000000000000080E0000FA0027857F4C828000051C1131D00003F122060000000000000800000FA0027";



static PROGMEM prog_uint32_t crc_table[16] = {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
};

unsigned long crc_update(unsigned long crc, byte data)
{
byte tbl_idx;
tbl_idx = crc ^ (data >> (0 * 4));
crc = pgm_read_dword_near(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
tbl_idx = crc ^ (data >> (1 * 4));
crc = pgm_read_dword_near(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
return crc;
}

unsigned long crc_string( unsigned char*s)
{
unsigned long crc = ~0L;
while (*s)
crc = crc_update(crc, *s++);

crc = ~crc;
return crc;
}

void setup(){
Serial.begin(9600);
Serial.print(crc_string(sample),HEX);

}

void loop() // run over and over
{

}

最佳答案

你的 crc_string() 函数正在做:

while (*s)
crc = crc_update(crc, *s++);

它将在第一个空字节处停止——我想你想循环字节数组的整个长度(这不是一个以零结尾的字符串),我猜它是 90 个字节。即

unsigned long crc_string( unsigned char*s, unsigned int length)
{
unsigned long crc = ~0L;
unsigned int i;
for(i=0; i<length; i++)
crc = crc_update(crc, *s++);

crc = ~crc;
return crc;
}

并调用crc_string(sample,90)

请注意,您注释的字符串 828180300000214611D0... 是垃圾,因为零字节由单个“0”而不是“00”表示。

关于c++ - 在 C++ 中使用字符指针从字符数组中读取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com