Practical Hex Conversion
Real-World Hex Conversion Techniques
Hex conversion is crucial in various programming scenarios, from network programming to cryptography and data encoding.
Color Representation Conversion
package main
import (
"fmt"
"strconv"
)
func hexToRGB(hexColor string) (int, int, int) {
// Remove ## if present
hexColor = hexColor[1:]
// Parse RGB components
r, _ := strconv.ParseInt(hexColor[:2], 16, 32)
g, _ := strconv.ParseInt(hexColor[2:4], 16, 32)
b, _ := strconv.ParseInt(hexColor[4:], 16, 32)
return int(r), int(g), int(b)
}
func main() {
r, g, b := hexToRGB("#3A7CA5")
fmt.Printf("RGB: (%d, %d, %d)\n", r, g, b)
}
Hex Conversion Workflow
graph TD
A[Input Hex Value] --> B{Conversion Type}
B --> C[Color Conversion]
B --> D[Network Address]
B --> E[Cryptographic Encoding]
Common Conversion Types
Conversion Type |
Use Case |
Example |
Color to RGB |
Web Design |
#FF0000 → (255, 0, 0) |
MAC Address |
Network |
00:1A:2B:3C:4D:5E |
IP Address |
Networking |
C0A80001 → 192.168.0.1 |
Network Address Conversion
func hexIPToDecimal(hexIP string) string {
// Convert hex IP to decimal
ipInt, _ := strconv.ParseInt(hexIP, 16, 64)
// Convert to dotted decimal
ip := fmt.Sprintf("%d.%d.%d.%d",
(ipInt >> 24) & 0xFF,
(ipInt >> 16) & 0xFF,
(ipInt >> 8) & 0xFF,
ipInt & 0xFF)
return ip
}
func main() {
decimalIP := hexIPToDecimal("C0A80001")
fmt.Println("IP Address:", decimalIP)
}
Advanced Hex Manipulation
func bitManipulationWithHex() {
// Bitwise operations with hex
a := 0x0F // Binary: 00001111
b := 0xF0 // Binary: 11110000
fmt.Printf("AND: 0x%X\n", a & b)
fmt.Printf("OR: 0x%X\n", a | b)
fmt.Printf("XOR: 0x%X\n", a ^ b)
}
- Use built-in conversion functions
- Handle potential parsing errors
- Choose appropriate conversion method
At LabEx, we emphasize practical hex conversion skills for efficient Go programming.