Blake Rivell
Blake Rivell

Reputation: 13875

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.

Upvotes: 2

Views: 2446

Answers (2)

Blake Rivell
Blake Rivell

Reputation: 13875

After further research and trying to follow the exact Steam Id documentation here is the solution I came up with:

STEAM_X:Y:Z

The formula from the documentation: W=Z*2+V+Y

Using STEAM_1:1:66138017 as an example:

var steamId = "STEAM_1:1:66138017";
var match = Regex.Match(steamId, @"^STEAM_[0-5]:[01]:\d+$", RegexOptions.IgnoreCase);

if (!match.Success)
{
    return null;
}

// Split it into 3 parts using ":"
var split = steamId.Split(":");

var v = 76561197960265728;
var y = long.Parse(split[1]);
var z = long.Parse(split[2]);

var w = (z * 2) + v + y;

return w;

Explanation on where V came from:

In the documentation there is a table that lists all of the Steam Account types. The most common account type is Individual. The table shows that the hex for this is 0x0110000100000000. Using a hex to decimal converter I ended up with 76561197960265728.

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 416039

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

Upvotes: 6

Related Questions