Search code examples
c#stringuint16ushort

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.


Solution

  • 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);