Introduction to Number Systems
Computers use binary, octal, and hexadecimal number systems for different purposes. Understanding these number systems is essential when programming in languages like Go.
Binary Numbers
The binary number system uses only two digits, 0 and 1. It is the foundation of all computer operations. In binary, each digit represents a power of 2.
Basic Example in Go
package main
import "fmt"
func main() {
// Binary representation
b := 0b1011 // 11 in binary
fmt.Printf("The binary number 0b1011 == %d in decimal\n", b)
}Octal Numbers
The octal number system uses eight digits, from 0 to 7. It is often used in computer systems for concise binary representations.
Basic Example in Go
package main
import "fmt"
func main() {
// Octal representation
o := 013 // 11 in octal, leading zero indicates octal
fmt.Printf("The octal number 013 == %d in decimal\n", o)
}Hexadecimal Numbers
The hexadecimal number system uses sixteen digits, from 0 to 9 and A to F, where A to F represent 10 to 15. It's widely used in computing as a human-friendly representation of binary values.
Basic Example in Go
package main
import "fmt"
func main() {
// Hexadecimal representation
h := 0xF // 15 in hexadecimal
fmt.Printf("The hexadecimal number 0xF == %d in decimal\n", h)
}Intermediate Operations
In Go, you can convert between these number systems using the strconv package.
Converting Numbers in Go
package main
import (
"fmt"
"strconv"
)
func main() {
// Decimal to binary
bin := strconv.FormatInt(11, 2)
fmt.Printf("Decimal 11 in binary is %s\n", bin)
// Decimal to octal
oct := strconv.FormatInt(11, 8)
fmt.Printf("Decimal 11 in octal is %s\n", oct)
// Decimal to hexadecimal
hex := strconv.FormatInt(15, 16)
fmt.Printf("Decimal 15 in hexadecimal is %s\n", hex)
}Advanced Topics
Working with binary, octal, and hexadecimal can sometimes involve bitwise operations, which are frequently used in systems programming and performance-sensitive code.
Working with Bitwise Operations in Go
package main
import "fmt"
func main() {
a := 1 << 1 // left shift by 1
fmt.Printf("1 shifted left by 1 is %d\n", a)
b := 1 | 1 // bitwise OR
fmt.Printf("1 OR 1 is %d\n", b)
inverted := ^60
fmt.Printf("Bitwise NOT of 60 is %d\n", inverted)
result := 5 & 3
fmt.Printf("5 AND 3 is %d\n", result)
toggle := 12 ^ 5
fmt.Printf("12 XOR 5 is %d\n", toggle)
}Mastering these concepts and operations in Go enhances your ability to write more efficient and effective code that interacts closely with hardware or requires meticulous performance tuning.