go - 如何在 Go 中定义位文字?

标签 go

有什么方法可以在 Golang (1.12v) 中像在 C 和其他一些语言中一样定义像 var i=0b0001111 这样的位文字?

最佳答案

The Go Programming Language Specification
Version of May 14, 2019

Integer 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/

相关文章:

go - 用一个值替换多个索引

json - 使用 2 层深的元素解码 JSON

html - go/golang 服务器中的静态 css 文件

go - 在 golang 中保存随机状态

go - Redigo:如何使用 Golang 从 Redis 获取键值映射?

GORM协会

跨多个服务器的 Golang 文件和文件夹复制/镜像

html - 将选择的数据返回到包含键值对的下拉表单元素

go - 模型没有主键

go - 使用反射获取指向值的指针