有什么方法可以在 Golang (1.12v) 中像在 C 和其他一些语言中一样定义像 var i=0b0001111
这样的位文字?
最佳答案
The Go Programming Language Specification
Version of May 14, 2019Integer literals
An integer literal is a sequence of digits representing an integer constant. An optional prefix sets a non-decimal base: 0b or 0B for binary, 0, 0o, or 0O for octal, and 0x or 0X for hexadecimal. A single 0 is considered a decimal zero. In hexadecimal literals, letters a through f and A through F represent values 10 through 15.
For readability, an underscore character _ may appear after a base prefix or between successive digits; such underscores do not change the literal's value.
int_lit = decimal_lit | binary_lit | octal_lit | hex_lit . decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] . binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits . octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits . hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits . decimal_digits = decimal_digit { [ "_" ] decimal_digit } . binary_digits = binary_digit { [ "_" ] binary_digit } . octal_digits = octal_digit { [ "_" ] octal_digit } . hex_digits = hex_digit { [ "_" ] hex_digit } .
对于 Go 1.13 及更高版本,使用二进制或十六进制:
package main
import "fmt"
func main() {
b := byte(0b00010011)
fmt.Printf("%08b %02x\n", b, b)
x := byte(0x13)
fmt.Printf("%08b %02x\n", x, x)
}
输出:
00010011 13
00010011 13
对于 Go 1.12 及更早版本,使用十六进制:
package main
import "fmt"
func main() {
x := byte(0x13)
fmt.Printf("%08b %02x\n", x, x)
}
输出:
00010011 13
关于go - 如何在 Go 中定义位文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56605810/