英文:
How to convert an integer to binary form in Go and vice versa
问题
我如何将整数转换为二进制形式?
我目前正在编写一个程序,它接受一个整数并将其转换为二进制形式。
它还应该接受二进制数并将其反转并转换回整数并打印出来。
例如:
12 -> 1100 -> 0011 -> 3
所以这个程序基本上应该:
输入:12
输出:3
package main
import (
"fmt"
"strconv"
)
var j int
func main() {
fmt.Scan(&j)
n := int64(j)
y := strconv.FormatInt(n, 2)
fmt.Println(y)
reverse(y)
}
func reverse(y string) {
}
英文:
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
package main
import (
"fmt"
"strconv"
)
var j int
func main() {
fmt.Scan(&j)
n := int64(j)
y := strconv.FormatInt(n, 2)
fmt.Println(y)
reverse(y)
}
func reverse(y string) {
}
答案1
得分: 4
你可能想要使用encoding/binary。
示例(goplay):
package main
import "fmt"
import "encoding/binary"
import "bytes"
func main() {
j := int32(5247)
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, j)
if err != nil {
fmt.Println(err)
return
}
var k int32
err = binary.Read(buf, binary.BigEndian, &k)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(k)
}
英文:
You probably want to use encoding/binary.
Example (goplay):
package main
import "fmt"
import "encoding/binary"
import "bytes"
func main() {
j := int32(5247)
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, j)
if err != nil {
fmt.Println(err)
return
}
var k int32
err = binary.Read(buf, binary.BigEndian, &k)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(k)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论