如何在Go中将整数转换为二进制形式,反之亦然

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

How to convert an integer to binary form in Go and vice versa

问题

我如何将整数转换为二进制形式?

我目前正在编写一个程序,它接受一个整数并将其转换为二进制形式。
它还应该接受二进制数并将其反转并转换回整数并打印出来。

例如:

12 -> 1100 -> 0011 -> 3

所以这个程序基本上应该:
输入:12
输出:3

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. var j int
  7. func main() {
  8. fmt.Scan(&j)
  9. n := int64(j)
  10. y := strconv.FormatInt(n, 2)
  11. fmt.Println(y)
  12. reverse(y)
  13. }
  14. func reverse(y string) {
  15. }
英文:

How do i convert an Integer to binary form?

I'm currently working on a program that takes an integer and converts it to binary form.
It should also take the binary number and reverse it and convert it back to an integer and print it out.

i.e.

> <code>12 -> 1100 -> 0011 -> 3</code>

So the program should basically:
Input: 12
Output: 3

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;strconv&quot;
  5. )
  6. var j int
  7. func main() {
  8. fmt.Scan(&amp;j)
  9. n := int64(j)
  10. y := strconv.FormatInt(n, 2)
  11. fmt.Println(y)
  12. reverse(y)
  13. }
  14. func reverse(y string) {
  15. }

答案1

得分: 4

你可能想要使用encoding/binary

示例(goplay):

  1. package main
  2. import "fmt"
  3. import "encoding/binary"
  4. import "bytes"
  5. func main() {
  6. j := int32(5247)
  7. buf := new(bytes.Buffer)
  8. err := binary.Write(buf, binary.BigEndian, j)
  9. if err != nil {
  10. fmt.Println(err)
  11. return
  12. }
  13. var k int32
  14. err = binary.Read(buf, binary.BigEndian, &k)
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. fmt.Println(k)
  20. }
英文:

You probably want to use encoding/binary.

Example (goplay):

  1. package main
  2. import &quot;fmt&quot;
  3. import &quot;encoding/binary&quot;
  4. import &quot;bytes&quot;
  5. func main() {
  6. j := int32(5247)
  7. buf := new(bytes.Buffer)
  8. err := binary.Write(buf, binary.BigEndian, j)
  9. if err != nil {
  10. fmt.Println(err)
  11. return
  12. }
  13. var k int32
  14. err = binary.Read(buf, binary.BigEndian, &amp;k)
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. fmt.Println(k)
  20. }

huangapple
  • 本文由 发表于 2013年4月5日 01:13:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/15817536.html
匿名

发表评论

匿名网友

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

确定