Go – 将表示二进制数的字符串转换为整数

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

Go - convert string which represent binary number into int

问题

我为此写了一个愚蠢的解决方案,有更好的方法吗?
如你所见,有很多无用的转换。

package main

import (
    "fmt"
    "strconv"
    "math"
)

func conv(str string) int {
    l := len(str)
    result := 0.0
    for i,n := range str {
        number,_ := strconv.Atof64(string(n))
        result += math.Exp2(float64(l-i-1))*number
    }
    return int(result)
}

func main() {
    fmt.Println(conv("1001"))
}
英文:

I wrote a stupid solution for this, any better recipe?
As you can see lots of useless conversions there.

package main

import (
    "fmt"
    "strconv"
    "math"
)

func conv(str string) int {
    l := len(str)
    result := 0.0
    for i,n := range str {
        number,_ := strconv.Atof64(string(n))
        result += math.Exp2(float64(l-i-1))*number
    }
    return int(result)
}

func main() {
    fmt.Println(conv("1001"))
}

答案1

得分: 45

你需要strconv.ParseInt函数,它可以将任意进制的字符串转换为给定位数的整数。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	if i, err := strconv.ParseInt("1001", 2, 64); err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(i)
	}
}

<kbd>Playground</kbd>

英文:

You want the strconv.ParseInt function, which converts from an arbitrary base, into a given bit size.

package main

import (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

func main() {
	if i, err := strconv.ParseInt(&quot;1001&quot;, 2, 64); err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(i)
	}
}

<kbd>Playground</kbd>

答案2

得分: 8

例如,在Go 1上,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	i, err := strconv.ParseInt("1101", 2, 64)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(i)
}

输出:

13
英文:

For example, on Go 1,

package main

import (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

func main() {
	i, err := strconv.ParseInt(&quot;1101&quot;, 2, 64)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(i)
}

Output:

13

答案3

得分: 0

package main

import (
	"fmt"
)

var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

func convertBase(num, fromBase, toBase int) string {
	if num == 0 {
		return "0"
	}

	var result []byte

	n := num
	if n < 0 {
		n = -n
		result = append(result, '-')
	}

	var stack []int
	for n > 0 {
		remainder := n % toBase
		stack = append(stack, remainder)
		n /= toBase
	}

	for len(stack) > 0 {
		result = append(result, digits[stack[len(stack)-1]])
		stack = stack[:len(stack)-1]
	}

	return string(result)
}

func main() {
	var num, fromBase, toBase int

	fmt.Print("Enter the number: ")
	fmt.Scanln(&num)

	fmt.Print("Enter the base of origin: ")
	fmt.Scanln(&fromBase)

	fmt.Print("Enter the base destination: ")
	fmt.Scanln(&toBase)

	// Convert from the original base to decimal first
	decimalNum := 0
	n := num
	p := 1
	for n > 0 {
		remainder := n % 10
		decimalNum += remainder * p
		n /= 10
		p *= fromBase
	}

	// Convert the decimal number to the desired base
	result := convertBase(decimalNum, 10, toBase)

	fmt.Printf("%v based on %v = %v based on %v.\n", num, fromBase, result, toBase)
}
英文:
package main

import (
	&quot;fmt&quot;
)

var digits = &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;

func convertBase(num, fromBase, toBase int) string {
	if num == 0 {
		return &quot;0&quot;
	}

	var result []byte

	n := num
	if n &lt; 0 {
		n = -n
		result = append(result, &#39;-&#39;)
	}

	var stack []int
	for n &gt; 0 {
		remainder := n % toBase
		stack = append(stack, remainder)
		n /= toBase
	}

	for len(stack) &gt; 0 {
		result = append(result, digits[stack[len(stack)-1]])
		stack = stack[:len(stack)-1]
	}

	return string(result)
}

func main() {
	var num, fromBase, toBase int

	fmt.Print(&quot;Enter the number: &quot;)
	fmt.Scanln(&amp;num)

	fmt.Print(&quot;Enter the base of origin: &quot;)
	fmt.Scanln(&amp;fromBase)

	fmt.Print(&quot;Enter the base destination: &quot;)
	fmt.Scanln(&amp;toBase)

	// Convert from the original base to decimal first
	decimalNum := 0
	n := num
	p := 1
	for n &gt; 0 {
		remainder := n % 10
		decimalNum += remainder * p
		n /= 10
		p *= fromBase
	}

	// Convert the decimal number to the desired base
	result := convertBase(decimalNum, 10, toBase)

	fmt.Printf(&quot;%v based on %v = %v based on %v.\n&quot;, num, fromBase, result, toBase)
}

huangapple
  • 本文由 发表于 2012年2月14日 11:53:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/9271469.html
匿名

发表评论

匿名网友

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

确定