简体   繁体   中英

Convert CRC function from C++ to C#

I am trying to convert this function from C++

BYTE serial::CalcCRC(BYTE start, const BYTE *buffer, DWORD lenght) 
{
    BYTE CRC = start; //...
    for(DWORD count = 0 ; count < lenght ; count++) CRC += buffer[count];
    return (0-CRC);
}

to C#. This is my C# code:

 public byte CalcCRC(byte start, byte[] buffer, int length)
 {
     byte crc = start;
     for (int i = 0; i < length; i++) crc += buffer[i];
     return (0 - crc);
 }

But I get this error on the last line:

error CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

How can I convert above function to C#? Also I think that C++ function may overflow most of the times, will I get same behaviour on C# side?

Ok now that I think cast may solve the error - but will I get same behaviour with my C# function as with C++ function, mainly due to the behaviour which may occur on overflow, etc.

Problem is that your original byte is converted into a integer the moment you do "0 - crc". So what you will need to do is have the last line

return (byte)(0-crc);

And that should fix the problem.

The reason it "converts" itself into a integer is that the numeric value is per default a integer. And doing Integer - Byte = Integer

EDIT: About the overflow will not happen, but to avoid possible problems you can make sure that the value does not exceed 255

So what you will have to do is have an additional check

if( crc + buffer[i] < Byte.MaxValue )
    crc += buffer[i];

Here's how I would translate that

public byte CalcCRC(byte start, byte[] buffer)
{
    unchecked
    {
        byte crc = start;
        for (int i = 0; i < buffer.Length; i++)
            crc += buffer[i];
        return (byte)(0 - crc);
    }
}

The unchecked will make sure that the overflow will not result in an exception. While that is the default, it can be changed as a compiler option.

The main difference here is that this will not allow you to enter a length that doesn't match up with the actual length of the array. In C++ that would have undefined behavior while in C# it would throw an exception because C# has array bounds checking.

And overflow is the same in both C# and C++ in that the left most binary digits are truncated based on the size of the data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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