英文:
Golang - Is there a bcadd/bcsub package?
问题
在Golang中是否有类似于PHP函数bcsub、bcadd等的包?
我正在尝试将以下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()
}
- 编辑:还添加了反向函数。
英文:
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()
}
- edit: added the reverse function as well
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论