如何将代码从C#翻译为C++;对于CRC函数?
我用C#编写了下面的代码来计算CRC,它的工作原理与我所希望的一样如何将代码从C#翻译为C++;对于CRC函数?,c#,c++,crc,code-translation,C#,C++,Crc,Code Translation,我用C#编写了下面的代码来计算CRC,它的工作原理与我所希望的一样 public byte crc_8(byte[] byteArray) { ushort reg_crc = 0; for(int i = 0; i<byteArray.Length; i++) { reg_crc ^= byteArray[i]; for(int j = 0; j < 8; j++)
public byte crc_8(byte[] byteArray)
{
ushort reg_crc = 0;
for(int i = 0; i<byteArray.Length; i++)
{
reg_crc ^= byteArray[i];
for(int j = 0; j < 8; j++)
{
if((reg_crc & 0x01) == 1)
{
reg_crc = (ushort)((reg_crc >> 1) ^ 0xE5);
}
else
{
reg_crc = (ushort)(reg_crc >> 1);
}
}
}
reg_crc = (byte)(reg_crc & 0xFF);
return (byte)reg_crc;
}
<>数组在C++中工作有点不同。它们不是物体;它们基本上只是在内存中重复的数据类型。在您的情况下,它将是一个重复的
uint\u 8
RX\u数据包大小次。你不能传递数组本身;而是将指针传递给数组的第一个元素。这是代码的C++版本:
uint8_t crc_8(uint8_t* byteArray, size_t length)
{
uint8_t reg_crc = 0;
for(int i = 0; i < length; i++)
{
reg_crc ^= byteArray[i];
for(int j = 0; j < 8; j++)
{
if((reg_crc & 0x01) == 1)
{
reg_crc = (reg_crc >> 1) ^ 0xE5;
}
else
{
reg_crc = reg_crc >> 1;
}
}
}
return reg_crc;
}
未来的有用提示:
C++标准库提供了一个名为
编写一个重载,以便只传递一个向量:crc_8
// The & after std::vector<uint8_t> means that it'll pass
// by reference, instead of passing by value. Passing by
// reference is usually the preferable option because nothing
// gets copied, making it much faster.
uint8_t crc_8(std::vector<uint8_t>& bytes) {
//This calls the the version shown above
return crc_8(bytes.data(), bytes.size());
}
//std::vector之后的&after表示它将通过
//通过引用,而不是通过值传递。路过
//参考通常是更好的选择,因为没有
//被复制,使它更快。
uint8_t crc_8(标准::向量和字节){
//这将调用上面显示的版本
返回crc_8(bytes.data(),bytes.size());
}
如果编译器说未定义
uint8\t
,那是因为需要将\include
放在文件的顶部。那么问题出在哪里?在C++中你尝试过哪些与C版本不一样的工作?我的问题是我不知道如何将代码从C语言翻译成C++。然而,我在下面得到的答案有帮助;还包括在内吗?不,不应该。赋值已产生一个字节。
uint8_t crc_8(uint8_t* byteArray, size_t length = RX_PACKET_SIZE)
{
uint8_t reg_crc = 0;
for(int i = 0; i < length; i++)
{
reg_crc ^= byteArray[i];
for(int j = 0; j < 8; j++)
{
if((reg_crc & 0x01) == 1)
{
reg_crc = (reg_crc >> 1) ^ 0xE5;
}
else
{
reg_crc = reg_crc >> 1;
}
}
}
return reg_crc;
}
// The & after std::vector<uint8_t> means that it'll pass
// by reference, instead of passing by value. Passing by
// reference is usually the preferable option because nothing
// gets copied, making it much faster.
uint8_t crc_8(std::vector<uint8_t>& bytes) {
//This calls the the version shown above
return crc_8(bytes.data(), bytes.size());
}