为什么这个在Go语言中从rune字符串转换为整数的转换不起作用?

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

Why does this conversion in go from a rune-string to integer does not work?

问题

我有以下代码:

我了解Go语言中的符文,我在过去几个小时里阅读了很多关于它们的内容,我试图解决这个问题...

package main

import (
    "fmt"
    "strconv"
)

func main() {
    e := "\x002"
    fmt.Println(e)
    new := string(e)
    i, err := strconv.Atoi(new)
    if err != nil { fmt.Println(err) }
    fmt.Println(i)
}

结果是:

2

strconv.ParseInt:解析"\x002"时出现无效语法

0

为什么我不能将字符串转换为整数?

任何帮助都将不胜感激!

英文:

i have the following code:

I know about runes in go, i read about them a lot in the last hours i have tried to solve this...

package main

import (
    "fmt"
    "strconv"
)

func main() {
    e := "\x002"
    fmt.Println(e)
    new := string(e)
    i, err := strconv.Atoi(new)
    if err != nil { fmt.Println(err) }
    fmt.Println(i)
}

result is:

2

strconv.ParseInt: parsing "\x002": invalid syntax

0

why can't i convert the string to an integer?

Any help appreciated!

答案1

得分: 2

我不100%确定你的目标,但看起来你想从包含给定字符的字符串中提取符文的整数值。

你想要的代码如下:

e := "\x02"
runes := []rune(e)
i := runes[0]
fmt.Println(i) // 2
英文:

I'm not 100% sure of your goal but it looks like you want to extract the int value of the rune you get from a string containing a given character.

It looks like you want

e := "\x02"
runes := []rune(e)
i := runes[0]
fmt.Println(i) // 2

答案2

得分: 0

\xXXXX试图将其解析为Unicode符文,你需要跳过\检查这里

可以使用以下方式:

e := "\x002"
#或者使用原始字符串:
e := `\x002`

编辑:

你为什么认为\x002是一个有效的整数?你是不是指的是0x002

英文:

\xXXXX tries to parse it as a unicode rune, you need to skip the \ check this:

Either use :

e := "\\x002"
#or use a raw string :
e := `\x002`

edit :

Why do you think \x002 is a valid integer? do you mean 0x002?

huangapple
  • 本文由 发表于 2014年5月16日 21:49:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/23696881.html
匿名

发表评论

匿名网友

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

确定