简体   繁体   中英

How to define bit literals in Go?

有什么方法可以像在 C 和其他一些语言中一样在 Golang ( 1.12v ) 中定义像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 } .

For Go 1.13 and later, use binary or hexadecimal:

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)
}

Output:

00010011 13
00010011 13

For Go 1.12 and earlier, use hexadecimal:

package main

import "fmt"

func main() {
    x := byte(0x13)
    fmt.Printf("%08b %02x\n", x, x)
}

Output:

00010011 13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM