Search code examples
c#steamsteam-web-apisteamworks-api

Converting a users Steam ID from console to the 64bit version in C#


I am creating an application where someone can paste a user's steam ID in a search box. In most cases it is going to be the steam ID from the in-game console which looks like: STEAM_1:0:12345678. I need to take this and convert it to the 64bit version in order to make requests to the Steam API for that user.

There is a lot of useful information here: https://developer.valvesoftware.com/wiki/SteamID

But I still can't figure out how to do the conversion to 64bit.


Solution

  • It's your lucky day; I wrote the whole thing for you. Normally we expect to see some effort in your own implementation first, even if it's rough, and we help you fix issues with that code.

    public static Int64 TranslateSteamID(string steamID)
    {
        Int64 result = 0;
    
        var template = new Regex(@"STEAM_(\d):([0-1]):(\d+)");
        var matches = template.Matches(steamID);
        if (matches.Count <= 0) return 0;
        var parts = matches[0].Groups;
        if (parts.Count != 4) return 0;
    
        Int64 x = Int64.Parse(parts[1].Value) << 24;
        Int64 y = Int64.Parse(parts[2].Value);
        Int64 z = Int64.Parse(parts[3].Value) << 1;
    
        result =  ((1 + (1 << 20) + x) << 32) | (y + z);        
        return result;
    }
    

    It at least works for the sample value on the linked page. You can try it here:

    https://dotnetfiddle.net/Ejrqcw