简体   繁体   中英

Converting VB6 varables to C#

I am converting old VB6 code and am having an issue with these constants:

VB6 code:

Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000

C# code:

private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;

Why does the second line have to be uint ? If I do it as int, it gives me an error?

The correct C# translation is:

const int GENERIC_READ = unchecked((int)0x80000000);

In VB, 'GENERIC_READ' is implicitly an Integer with a negative value. The only way to reproduce this in C# is to cast the unsigned integer literal to an int in an unchecked context.

The source of the confusion is a historical difference between VB and C# regarding hex literals: 0x80000000 == 2147483648 in C# but not in VB.NET

In the absence of a type suffix on the literal, hex literals in VB.NET are either of type Integer or Long, never unsigned types.

The maximum value of Int32 is 2,147,483,647, and the value of 0x80000000 is 2,147,483,648, or Int32.MaxValue + 1 .

Using a uint (or long ) gives you a type that's large enough to hold the value you are assigning.

The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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