What is base argument used for in ParseInt()?

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

What is base argument used for in ParseInt()?

问题

每当我们尝试将字符串转换为整数时,我经常遇到这样的示例代码:

parseValue, err := strconv.ParseInt(value, 10, 64)

所以上述代码中的ParseInt()有三个参数。根据文档中的代码:

func ParseInt(s string, base int, bitSize int) (i int64, err error) {

我试图理解这里的base int,所以我将值从0更改为16。PlayGolang

当输入为010时,结果是正确的。除了010之外的数字会导致恐慌。我仍然感到困惑,不明白这里的baseParseInt()中的作用是什么?有人可以解释一下吗?

英文:

I have come across many sample code whenever we try to convert string to int we use :

parseValue, err := strconv.ParseInt(value, 10, 64)

So the code above ParseInt() has three arguments. from the documentation code :

func ParseInt(s string, base int, bitSize int) (i int64, err error) {

I tried to understand the base inthere so I change the value from 0 to 16. PlayGolang.

The result is ok when the input are 0 and 10. Number other that 0 and 10 are panic. I still confused and not understand. Can someone explain what base is used for in ParseInt()?

答案1

得分: 1

你正在将一个字符串转换为整数。该方法要求你提供字符串所在的基数(数制)。你可以在这里了解更多关于数制的知识:https://en.wikipedia.org/wiki/Radix

例如(使用你提供的代码片段):

var s string = "1111" // 这个字符串是二进制的(基数为2)
i, err := strconv.ParseInt(s, 2, 64) // 将基数设为2

结果:

你好,15,类型为int64!
英文:

You are converting a string to an integer. The method is asking you for the base (number system) the string is in. You can learn more about number systems here: https://en.wikipedia.org/wiki/Radix

For example (using your code snippet provided here):

var s string = "1111" // This string is in binary (Base 2)
i, err := strconv.ParseInt(s, 2, 64) // Give the base as 2

Result:

Hello, 15 with type int64!

huangapple
  • 本文由 发表于 2017年2月28日 11:27:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/42499643.html
匿名

发表评论

匿名网友

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

确定