I'm really confused as to why the following code gives me different results when run in VB.NET as opposed to 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.
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?
The C# code, btw, is:
int pos = x[15] << 1;
for (int i = 14; i >= 0; --i)
{
pos = x[i] << 1;
}
CodePudding user response:
From the documentation for the 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. If the left-hand operand is of another integral type (sbyte, byte, short, ushort, or char), its value is converted to the int type
[Emphasis mine.]
From the documentation for the 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:
pos = CInt(x(i)) << 1