CRC8 checksum function translation from C# to VB.N

2019-09-16 02:15发布

I'm having a problem to translate following code from C# to VB.NET.

C# code

public static byte Crc8(byte[] data, int size) {
    byte checksum = 0;
    for (int i=0; i<=size; i++)
        checksum += data[i];

    return (byte)(-checksum);
}

VB.NET code

Public Shared Function Crc8(ByVal data As Byte(), ByVal size As Integer) As Byte
    Dim checksum As Byte = 0
    For i As Integer = 0 To size - 1
        checksum += data(i)
    Next

    Return CByte(-checksum)
End Function

Problem is that the VB code results in a "Arithmetic operation resulted in an overflow." error.

It seems that the "+=" operator does not operate the same way. In VB it's actually creating a sum (100 + 200 = 300) and in C# it's performing some kind of operation on the bytes (100 + 200 = 44). I can't seem to find what operation it's doing.

标签: c# vb.net crc
2条回答
不美不萌又怎样
2楼-- · 2019-09-16 03:01

For future reference, the solution was:

Public Shared Function Crc8(ByVal data As Byte(), ByVal size As Integer) As Byte
        Dim checksum As Byte = 0
        For i As Integer = 0 To size - 1
            checksum = (CInt(checksum) + data(i)) Mod 256
        Next
        If checksum = 0 Then
            Return 0
        Else
            Return CByte(256 - checksum)
        End If
    End Function
查看更多
再贱就再见
3楼-- · 2019-09-16 03:02

The difference is that by default, C# handles overflow by just wrapping - so 255 + 1 will end up as 0. In VB - by default, again - the overflow throws System.OverflowException.

In C#, you can control this in a fine-grained way using the checked and unchecked keywords. You can also change the default for a whole project. So for example, in Noda Time I've turned on checked arithmetic in order to spot overflows, but I deliberate turn it off for hash code generation (where overflow is likely and harmless) by using an unchecked block.

Unfortunately as far as I can tell, VB doesn't have the fine-grained control. You can turn overflow checking off for a whole project using the "Remove Integer Overflow Checks" option, but you can't do it for just some sections of the code.

So in your case, you either need to move this bit of code to a different project where you can turn overflow checking off, or you need to live with overflow checking being off for your whole project.

(As an aside, it looks like this makes implementing GetHashCode in VB a bit of a pain.)

查看更多
登录 后发表回答