CRC8校验和功能从C#转换为VB.NET [英] CRC8 checksum function translation from C# to VB.NET

查看:289
本文介绍了CRC8校验和功能从C#转换为VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将以下代码从C#转换为VB.NET时遇到问题。

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

C#代码

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代码

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

问题是VB代码导致算术运算导致溢出。错误。

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

似乎 + =运算符的操作方式不同。在VB中,它实际上是创建一个和(100 + 200 = 300),在C#中,它是对字节执行某种运算(100 + 200 = 44)。
我似乎找不到执行的操作。

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#处理通过包装自动溢出-255 + 1最终将为0。在VB中-默认情况下,再次-溢出抛出 System.OverflowException

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.

在C#中,您可以使用选中的未选中关键字。您还可以更改整个项目的默认设置。因此,例如,在Noda Time中,我打开了检查算法以发现溢出,但我故意将其关闭 ,以生成哈希代码(其中溢出可能并且无害 >)使用 unchecked 块。

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.

据我所知,VB没有细粒度的控制。您可以使用删除整数溢出检查选项来关闭整个项目的溢出检查,但是不能仅对部分代码执行此检查。

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.

(顺便说一句,这看起来使得在VB GetHashCode = https://stackoverflow.com/questions/4654227/overriding-gethashcode-in-vb-without-checked-unchecked-keyword-support>有点痛苦。)

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

这篇关于CRC8校验和功能从C#转换为VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆