How to define bit literals in Go?

Viewed 9786

Is there any way to define bit literals like var i=0b0001111 in Golang (1.12v) as in C and some other languages?

1 Answers

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
Related