简体   繁体   English

如何将此代码从C转换为C ++?

[英]How can I convert this code from C to C++?

I am working on an embedded project using an mbed. 我正在使用mbed开发嵌入式项目。 The chip's manufacturer specifies a Cyclical Redundancy Test using this lookup generator, but its written in C. Lookup Generator Code 芯片的制造商使用此查找生成器指定了循环冗余测试,但是用C编写。 查找生成器代码

    ///////////////////////configures CRC check lookup table////////////////////////
short pec15Table[256];
short CRC15_POLY = 0x4599;   //CRC code

void configCRC(void) 
{
    for (int i = 0; i < 256; i++)
    {
        remainder = i << 7;
        for (int bit = 8; bit > 0; --bit)
        {
            if (remainder & 0x4000)
            {
                remainder = ((remainder << 1));
                remainder = (remainder ^ CRC15_POLY)
            }
            else
            {
                remainder = ((remainder << 1));
            }
        }
    }
    pec15Table[i] = remainder&0xFFFF;
};

I am not really good with C++ yet, so I just copied and pasted it and checked for clear syntax errors. 我对C ++还不是很满意,所以我只复制并粘贴了它,然后检查了清晰的语法错误。 For example I switched the int16 declarations with short and unsigned short. 例如,我将int16声明切换为short和unsigned short。 But, when I compile it gives me the following error. 但是,当我编译它时,出现以下错误。 Which doesn't make sense to me. 这对我来说没有意义。 I am sure im doing something wrong. 我确定我做错了什么。

Error: Cannot determine which instance of overloaded function "remainder"  is intended in "config.cpp", Line: 20, Col: 10

Obviously you have a namespace collision with std::remainder . 显然,您与std::remainder有名称空间冲突。 This is one of many reasons to avoid global variables. 这是避免全局变量的众多原因之一。 C and C++ should otherwise be identical here. 否则,C和C ++应该相同。

Notably though, this code is very naively written. 值得注意的是,该代码非常幼稚。 Not only must the function be rewritten to properly take parameters, but the type use is all over the place. 不仅必须重写函数以正确获取参数,而且类型用法无处不在。

You should never do bit-wise arithmetic on signed types, because that opens up for a lot of poorly-defined behavior bugs. 永远不要对带符号的类型进行按位算术,因为这会导致许多定义不当的行为错误。 All "sloppy typing" types like short and int must be replaced with types from stdint.h. 所有“ short类型”(如shortint类型都必须替换为stdint.h中的类型。 You should only use unsigned types. 您只能使用无符号类型。 You need to be aware of implicit integer promotion. 您需要了解隐式整数提升。

Just rename variable remainder to fremainder( or some other name as you wish) and see the magic in compilation. 只需将变量其余部分重命名为fremainder(或根据需要使用其他名称),然后在编译中看到魔术。

These kind of issues come into picture because of not following any standard convention while naming variable. 之所以出现这类问题,是因为在命名变量时没有遵循任何标准约定。

Check this link to see why renaming of variable is required 检查此链接以查看为什么需要重命名变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM