简体   繁体   English

在 VB.NET 到 C# 中显示不同结果的二进制移位

[英]Binary Shift displaying different results in VB.NET to C#

I'm really confused as to why the following code gives me different results when run in VB.NET as opposed to C#.我真的很困惑为什么以下代码在 VB.NET 而不是 C# 中运行时会给我不同的结果。 I've read that there are some binary shift differences between the two languages but I can't work out what I need to do to make VB.NET show the same answer for 'pos' as C# does.我已经读到这两种语言之间存在一些二进制移位差异,但我无法弄清楚我需要做什么才能使 VB.NET 对“pos”显示与 C# 相同的答案。

Imports System.Threading

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        MultiplyH({168, 238, 95, 83, 235, 11, 228, 190, 8, 58, 0, 0, 0, 0, 0, 0})


    End Sub

    Public Sub MultiplyH(ByVal x As Byte())

        Dim pos As Integer = x(15) << 1
        Dim i = 14
        While i >= 0
            pos = x(i) << 1
            Interlocked.Decrement(i)
        End While
    End Sub
End Class

The first eight answers for 'pos' are all the same (to be expected for the zeroes) but once i = 6, VB.NET shows pos = 124 whereas C# has pos = 380. Can anyone help me so that pos = 380 in VB.NET please? “ POS”的前八个答案都是相同的(预期为零),但是一旦i = 6,ZBD5C8A1AFE53C8BA44444F60C9AF6C03C25Z显示pos = 124,而ZD7EFA19FA19FBBAR 397D3972FD55ADB60222222223DD574CTHENCENT = 38.380.380.380. 380. 3880. ?

The C# code, btw, is:顺便说一句,C# 代码是:

int pos = x[15] << 1;
for (int i = 14; i >= 0; --i)
{
                pos = x[i] << 1;
}

From the documentation for the C# << operator :C# << operator 的文档中

Because the shift operators are defined only for the int, uint, long, and ulong types, the result of an operation always contains at least 32 bits.因为移位运算符仅针对 int、uint、long 和 ulong 类型定义,所以运算结果始终包含至少 32 位。 If the left-hand operand is of another integral type (sbyte, byte, short, ushort, or char), its value is converted to the int type如果左侧操作数是另一个整数类型(sbyte、byte、short、ushort 或 char),则其值将转换为 int 类型

[Emphasis mine.] [强调我的。]

From the documentation for the VB.NET << operator :VB.NET << operator 的文档中

The result always has the same data type as that of the expression being shifted.结果始终具有与被移位的表达式相同的数据类型。

To get the same result in VB.NET as in C#, you need to use:要在 VB.NET 中获得与 C# 中相同的结果,您需要使用:

pos = CInt(x(i)) << 1

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

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