Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Shift Differences between VB.NET and C#

I just found an interesting problem between translating some data:

VB.NET: CByte(4) << 8 Returns 4

But C#: (byte)4 << 8 Returns 1024

Namely, why does VB.NET: (CByte(4) << 8).GetType() return type {Name = "Byte" FullName = "System.Byte"}

Yet C#: ((byte)4 << 8).GetType() returns type {Name = "Int32" FullName = "System.Int32"}

Is there a reason why these two treat the binary shift the same? Following from that, is there any way to make the C# bit shift perform the same as VB.NET (to make VB.NET perform like C# you just do CInt(_____) << 8)?

like image 903
Seph Avatar asked Nov 16 '11 12:11

Seph


1 Answers

According to http://msdn.microsoft.com/en-us/library/a1sway8w.aspx byte does not have << defined on it for C# (only int, uint, long and ulong. This means that it will use an implciit conversion to a type that it can use so it converts it to int before doing the bit shift.

http://msdn.microsoft.com/en-us/library/7haw1dex.aspx says that VB defines the operation on Bytes. To prevent overflow it applies a mask to your shift to bring it within an appropriate range so it is actually in this case shifting by nothing at all.

As to why C# doesn't define shifting on bytes I can't tell you.

To actually make it behave the same for other datatypes you need to just mask your shift number by 7 for bytes or 15 for shorts (see second link for info).

like image 121
Chris Avatar answered Sep 19 '22 13:09

Chris