如何将十六进制长字符串解析为uint [英] How to parse long hexadecimal string into uint

查看:86
本文介绍了如何将十六进制长字符串解析为uint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要提取十六进制字符串形式的数据,我需要将其转换为十进制表示法,截断18个小数位,然后在JSON中使用.

I'm pulling in data that is in long hexadecimal string form which I need to convert into decimal notation, truncate 18 decimal places, and then serve up in JSON.

例如,我可能具有十六进制字符串:

For example I may have the hex string:

"0x00000000000000000000000000000000000000000000d3c21bcecceda1000000"

起初我尝试使用ParseUint(),但是由于它支持的最高级别是int64,所以我的电话号码最终太大了.

At first I was attempting to use ParseUint(), however since the highest it supports is int64, my number ends up being way too big.

此示例在转换和截断后的结果为10 ^ 6. 但是,在某些情况下,此数字最多可以为10 ^ 12(意味着截断为10 ^ 30!).

This example after conversion and truncation results in 10^6. However there are instances where this number can be up to 10^12 (meaning pre truncation 10^30!).

攻击此问题的最佳策略是什么?

What is the best strategy to attack this?

推荐答案

使用数学/大用于处理大于64位的数字.

Use math/big for working with numbers larger than 64 bits.

来自 Int.SetString 示例:

s := "d3c21bcecceda1000000"
i := new(big.Int)
i.SetString(s, 16)
fmt.Println(i)

https://play.golang.org/p/vf31ce93vA

math/big类型还支持encoding.TextMarshalerfmt.Scanner接口.

例如

i := new(big.Int)
fmt.Sscan("0x000000d3c21bcecceda1000000", i)

i := new(big.Int)
fmt.Sscanf("0x000000d3c21bcecceda1000000", "0x%x", i)

这篇关于如何将十六进制长字符串解析为uint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆