Work with binary and hexadecimal literals
Work with binary and hexadecimal literals
Integer literals can represent the same number in several bases. Decimal uses base ten, binary uses 0b with digits 0 and 1, octal uses 0o with digits 0 through 7, and hexadecimal uses 0x with digits 0 through 9 and A through F. Prefix letters may be uppercase too. These are numeric values, not strings.
package main
import "fmt"
func main() { fmt.Println(42, 0b101010, 0o52, 0x2A)}All four literals are 42. A binary digit position has weight 1, 2, 4, 8 and so on from right to left; a hex digit has weight 1, 16, 256 and so on. Thus 0x2A is 2*16 + 10.
Readable literals and formatted output
package main
import "fmt"
func main() { value := 0b1111_0000 fmt.Printf("%d %08b %02X\n", value, value, value) fmt.Println(1_000_000)}Underscores between digits improve readability without changing value. One underscore is also allowed immediately after a base prefix. In Printf, %d prints decimal, %08b prints binary padded to at least eight digits with zeros, and %02X prints uppercase hex padded to at least two digits. A leading zero without an explicit prefix denotes legacy octal: 010 is 8, not 10. Prefer explicit 0o when octal is intended.
Try it locally
Write decimal 255 as hexadecimal and binary literals. Print both using Println. Expected: 255 255.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 06: Work with binary and hexadecimal literals
Check the lesson objective before moving on.
What is 0x10 in decimal?
Which is a valid binary literal?