简体   繁体   中英

Concatenate strings, convert to ushort, compare against ushort

So I have some constants:

const ushort _WIN32_WINNT_NT4 = 0x0400;
const ushort _WIN32_WINNT_WIN2K = 0x0500;
....

And then I have a major version number, minor version number, and service pack number, that, when you concatenate those together, it's the same as the number above - except 2 of them are int and one is a string . I can get them all into a string like this:

string version = majorVersion.ToString() + minorVersion.ToString() + sp;

For Windows 2000, this would look like "500" . It "matches" the ushort, just without the 0x0 .

What I'd like to do is hand off version to a function, as a ushort that returns the correct OS:

private static string WindowsVersion(ushort uniNum)
{
    switch (uniNum)
    {
        case _WIN32_WINNT_NT4:
            return "Windows NT 4.0";
        case _WIN32_WINNT_WIN2K:
            return "Windows 2000";
        ....
        default:
            return "Unknown OS version.";
    }
 }

The problem is, even if I do:

ushort uniNum = Convert.ToUInt16(version);

And say it sends it in as 500 , the constant is 0x0500 , so it never finds the OS and returns Unknown OS version , instead. When I debug and hover over _WIN32_WINNT_WIN2K , it's actually 1280 in decimal format. _WIN32_WINNT_NT4 is showing as 1024 , so "400" would never match it.

And if I include the "0x0":

ushort uniNum = Convert.ToUInt16("0x0" + version);

It gives me an error that the input is in the incorrect format.

I'm probably missing something simple, but I can't find anything anywhere that's been helpful.

You already have the constants and they are hexadecimal. If you are getting 400 and 500 they are also hexadecimal, so replace:

ushort uniNum = Convert.ToUInt16(version);

with:

ushort uniNum = Convert.ToUInt16(version, 16);

Your constant declaration's value is a hexadecimal literal expression:

const ushort _WIN32_WINNT_NT4 = 0x0400;

Where 0x0400 is equivalent to hex 400 , decimal 1024 . So basically, you're not comparing to 400 but to 1024.

Change your constant to be 400 if you'd like to compare against 400:

const ushort _WIN32_WINNT_NT4 = 400;

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