Golang – 有没有一个 bcadd/bcsub 的包?

huangapple go评论113阅读模式
英文:

Golang - Is there a bcadd/bcsub package?

问题

在Golang中是否有类似于PHP函数bcsubbcadd等的包?

我正在尝试将以下PHP函数转换为Golang:

func convertToSteamID(communityID string) string {
    // 查看steamid中的第二个数字(auth服务器)是0还是1。奇数为1,偶数为0
    authserver := new(big.Int).Sub(communityID, big.NewInt(76561197960265728)).And(big.NewInt(1))
    // 获取steamid的第三个数字
    authid := new(big.Int).Sub(communityID, big.NewInt(76561197960265728)).Sub(authserver).Div(big.NewInt(2))
    // 将STEAM_前缀和第一个数字(始终为0)以及冒号与其他两个数字连接起来
    return "STEAM_0:" + authserver.String() + ":" + authid.String()
}
英文:

Is there a package in golang similar to the PHP functions bcsub, bcadd etc.?

I am trying to write the following function from php to golang.

function convertToSteamID($communityID) {
	// See if the second number in the steamid (the auth server) is 0 or 1. Odd is 1, even is 0
	$authserver = bcsub($communityID, '76561197960265728') & 1;
	// Get the third number of the steamid
	$authid = (bcsub($communityID, '76561197960265728')-$authserver)/2;
	// Concatenate the STEAM_ prefix and the first number, which is always 0, as well as colons with the other two numbers
	return "STEAM_0:$authserver:$authid";
}

答案1

得分: 0

你可以使用big.Int来完成这个任务:

var (
    magic, _ = new(big.Int).SetString("76561197960265728", 10)
    one      = big.NewInt(1)
    two      = big.NewInt(2)
)

func commIDToSteamID(ids string) string {
    id, _ := new(big.Int).SetString(ids, 10)
    id = id.Sub(id, magic)
    isServer := new(big.Int).And(id, one)
    id = id.Sub(id, isServer)
    id = id.Div(id, two)
    return "STEAM_0:" + isServer.String() + ":" + id.String()
}

func steamIDToCommID(ids string) string {
    p := strings.Split(ids, ":")
    id, _ := new(big.Int).SetString(p[2], 10)
    id = id.Mul(id, two)
    id = id.Add(id, magic)
    auth, _ := new(big.Int).SetString(p[1], 10)
    return id.Add(id, auth).String()
}

playground

  • 编辑:还添加了反向函数。
英文:

You can do it using big.Int:

var (
	magic, _ = new(big.Int).SetString("76561197960265728", 10)
	one      = big.NewInt(1)
	two      = big.NewInt(2)
)

func commIDToSteamID(ids string) string {
	id, _ := new(big.Int).SetString(ids, 10)
	id = id.Sub(id, magic)
	isServer := new(big.Int).And(id, one)
	id = id.Sub(id, isServer)
	id = id.Div(id, two)
	return "STEAM_0:" + isServer.String() + ":" + id.String()
}

func steamIDToCommID(ids string) string {
	p := strings.Split(ids, ":")
	id, _ := new(big.Int).SetString(p[2], 10)
	id = id.Mul(id, two)
	id = id.Add(id, magic)
	auth, _ := new(big.Int).SetString(p[1], 10)
	return id.Add(id, auth).String()
}

<kbd>playground</kbd>

  • edit: added the reverse function as well

huangapple
  • 本文由 发表于 2016年4月2日 09:57:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/36368343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定