英文:
Converting from an integer to its binary representation
问题
有没有人知道Go语言中是否有内置功能可以将任何一种数字类型转换为二进制形式。
例如,如果输入为123
,则输出为字符串"1111011"
。
英文:
Has anyone got an idea if there is any inbuilt functionality in Go for converting from any one of the numeric types to its binary number form.
For example, if 123
was the input, the string "1111011"
would be the output.
答案1
得分: 147
The strconv
package has FormatInt
function, which accepts an int64
and allows you to specify the base.
n := int64(123)
fmt.Println(strconv.FormatInt(n, 2)) // 1111011
DEMO: http://play.golang.org/p/leGVAELMhv
>http://golang.org/pkg/strconv/#FormatInt
>func FormatInt(i int64, base int) string
>FormatInt函数返回给定基数下i的字符串表示,其中2 <= base <= 36。结果使用小写字母'a'到'z'表示大于等于10的数字值。
英文:
The strconv
package has FormatInt
, which accepts an int64
and lets you specify the base.
n := int64(123)
fmt.Println(strconv.FormatInt(n, 2)) // 1111011
DEMO: http://play.golang.org/p/leGVAELMhv
>http://golang.org/pkg/strconv/#FormatInt
>func FormatInt(i int64, base int) string
>FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
答案2
得分: 81
参见fmt包:
n := int64(123)
fmt.Printf("%b", n) // 1111011
答案3
得分: 15
package main
import . "fmt"
func main(){
Printf("%d == %08b\n",0,0)
Printf("%d == %08b\n",1,1)
Printf("%d == %08b\n",2,2)
Printf("%d == %08b\n",3,3)
Printf("%d == %08b\n",4,4)
Printf("%d == %08b\n",5,5)
}
结果为:
0 == 00000000
1 == 00000001
2 == 00000010
3 == 00000011
4 == 00000100
5 == 00000101
英文:
package main
import . "fmt"
func main(){
Printf("%d == %08b\n",0,0)
Printf("%d == %08b\n",1,1)
Printf("%d == %08b\n",2,2)
Printf("%d == %08b\n",3,3)
Printf("%d == %08b\n",4,4)
Printf("%d == %08b\n",5,5)
}
results in:
0 == 00000000
1 == 00000001
2 == 00000010
3 == 00000011
4 == 00000100
5 == 00000101
答案4
得分: 11
这段代码适用于大整数 *big.Int
:
x := big.NewInt(123)
s := fmt.Sprintf("%b", x)
// s == "1111011"
因为 *big.Int
实现了 fmt.Formatter
接口。
引用自 https://stackoverflow.com/a/23317788/871134
英文:
This code works on big integers *big.Int
:
x := big.NewInt(123)
s := fmt.Sprintf("%b", x)
// s == "1111011"
because *big.Int
implements the fmt.Formatter
interface.
Taken from https://stackoverflow.com/a/23317788/871134
答案5
得分: 4
一个替代的方法是简单地执行以下操作:
s := fmt.Sprintf("%b", 123)
fmt.Println(s) // 1111011
为了获得更丰富的表示,您可以使用unsafe
包(强烈不推荐):
a := int64(123)
byteSliceRev := *(*[8]byte)(unsafe.Pointer(&a))
byteSlice := make([]byte, 8)
for i := 0; i < 8; i++ {
byteSlice[i] = byteSliceRev[7 - i]
}
fmt.Printf("%b\n", byteSlice)
这也适用于负整数。
英文:
An alternate way for the accepted answer would be to simply do
s := fmt.Sprintf("%b", 123)
fmt.Println(s) // 1111011
For a more rich representation you can use the unsafe
package(strongly discouraged) as
a := int64(123)
byteSliceRev := *(*[8]byte)(unsafe.Pointer(&a))
byteSlice := make([]byte, 8)
for i := 0; i < 8; i++ {
byteSlice[i] = byteSliceRev[7 - i]
}
fmt.Printf("%b\n", byteSlice)
This works for negative integers too.
答案6
得分: 3
建立在@Mark提供的答案基础上
尽管OP问如何打印一个整数,但我经常想查看超过64位的数据,而不让我的眼睛迷茫:
/* --- Credit to Dave C in the comments --- */
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Printf("<%s>\n", fmtBits([]byte{0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0x0D, 0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0x0D}))
// OUTPUT:
// <11011110 10101101 10111110 11101111 11110000 00001101 11011110 10101101 10111110 11101111 11110000 00001101>
}
func fmtBits(data []byte) []byte {
var buf bytes.Buffer
for _, b := range data {
fmt.Fprintf(&buf, "%08b ", b)
}
buf.Truncate(buf.Len() - 1) // To remove extra space
return buf.Bytes()
}
英文:
Building on the answer provided by @Mark
Although the OP asked how to print an integer, I often want to look at more then 64 bits worth of data, without my eyes boggling:
/* --- Credit to Dave C in the comments --- */
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Printf("<%s>\n", fmtBits([]byte{0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0x0D, 0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0x0D}))
// OUTPUT:
// <11011110 10101101 10111110 11101111 11110000 00001101 11011110 10101101 10111110 11101111 11110000 00001101>
}
func fmtBits(data []byte) []byte {
var buf bytes.Buffer
for _, b := range data {
fmt.Fprintf(&buf, "%08b ", b)
}
buf.Truncate(buf.Len() - 1) // To remove extra space
return buf.Bytes()
}
<iframe src="https://play.golang.org/p/ifobZWv_du" frameborder="0" style="width: 100%; height: 100%"><a href="https://play.golang.org/p/ifobZWv_du">see this code in play.golang.org</a></iframe>
答案7
得分: 3
不安全指针必须用于正确表示二进制格式中的负数。
package main
import (
"fmt"
"strconv"
"unsafe"
)
func bInt(n int64) string {
return strconv.FormatUint(*(*uint64)(unsafe.Pointer(&n)), 2)
}
func main() {
fmt.Println(bInt(-1))
}
https://play.golang.org/p/GxXjjWMyC4x
英文:
Unsafe pointers must be used to correctly represent negative numbers in binary format.
package main
import (
"fmt"
"strconv"
"unsafe"
)
func bInt(n int64) string {
return strconv.FormatUint(*(*uint64)(unsafe.Pointer(&n)), 2)
}
func main() {
fmt.Println(bInt(-1))
}
答案8
得分: 1
Many above answers do not work if you use negative decimals.
Here is the simplest answer. Also works with negative decimals.
var a int64 = -1
fmt.Printf("%b\n", uint64(a)) // 11111.... (not -1)
You can also use fmt.Sprintf
instead of fmt.Printf
if you want a string
variable.
This way, you can convert negative decimal into bitwise representation using two's complement (without -
sign), not into mathematical binary representation (using -
sign). (As I commented in Soslan's answer.)
(Soslan and Vaibhav's answers also work with negative numbers, using the unsafe
package.)
英文:
Many above answers do not work if you use negative decimals.
Here is the simplest answer. Also works with negative decimals.
var a int64 = -1
fmt.Printf("%b\n", uint64(a)) // 11111.... (not -1)
You can also use fmt.Sprintf
instead of fmt.Printf
if you want a string
variable.
This way, you can convert negative decimal into bitwise representation using two's complement (without -
sign), not into mathematical binary representation (using -
sign). (As I commented in Soslan's answer.)
(Soslan and Vaibhav's answers also work with negative numbers, using the unsafe
package.)
答案9
得分: 0
package main
import (
"bytes"
"encoding/binary"
"fmt"
"time"
)
func main() {
buf := new(bytes.Buffer)
var x = time.Now().UnixNano()
err := binary.Write(buf, binary.LittleEndian, x)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Printf("%v", buf.Bytes())
}
英文:
package main
import (
"bytes"
"encoding/binary"
"fmt"
"time"
)
func main() {
buf := new(bytes.Buffer)
var x = time.Now().UnixNano()
err := binary.Write(buf, binary.LittleEndian, x)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Printf("%v", buf.Bytes())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论