Home »
Golang
Hexadecimal Literals in Golang
By IncludeHelp Last updated : October 05, 2024
Hexadecimal numbers
Hexadecimal (Hex) is a number system with base 16, it has 16 values (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A/a, B/b, C/c, D/d, E/e, and F/f).
Hexadecimal Literals in Golang
In Go programming language, a hexadecimal literal can be written with a prefix 0x or 0X (Zero and X alphabet either in Uppercase or Lowercase). The value which is prefixed with 0x or 0X is considered as a hexadecimal value and it can be used in the program statements like a Hex value can be assigned to a variable or constant, can be used within an expression, can be assigned in an array, etc.
Examples:
0x123AF
0X123AF
0X345
0X AFC
0X00
0XFF
0XFFFFE
Assigning a hexadecimal value to a variable & constant
In the below example, we are creating a variable and a constant, and assigning hexadecimal values to them.
Example of assigning hexadecimal values to a variable & a constant
// Golang program to demonstrate the example of
// assigning hexadecimal values to
// a variable & a constant
package main
import (
"fmt"
)
func main() {
// variable
var a int = 0x123AF
// constant
const b int = 0xFF
// printing the values
fmt.Println("a = ", a)
fmt.Println("b = ", b)
// printing values in the hexadecimal format
fmt.Printf("a = %X\n", a)
fmt.Printf("b = %X\n", b)
}
Output:
a = 74671
b = 255
a = 123AF
b = FF
Using a hexadecimal value in an expression
A hexadecimal value can also be used within an expression. In the below program, we are declaring two variables, assigning them with hexadecimal values, and finding their sum with a hexadecimal value 0xFF which is equivalent to 255.
Example of using hexadecimal values in an expression
// Golang program to demonstrate the example of
// Example of using hexadecimal values
// in an expression
package main
import (
"fmt"
)
func main() {
// variables
a := 0x10
b := 0x20
// calculating the sum of a, b and 0xFF
c := a + b + 0xFF
// printing the values
fmt.Println("a = ", a)
fmt.Println("b = ", b)
fmt.Println("c = ", c)
// printing values in the hexadecimal format
fmt.Printf("a = %X\n", a)
fmt.Printf("b = %X\n", b)
fmt.Printf("c = %X\n", c)
}
Output:
a = 16
b = 32
c = 303
a = 10
b = 20
c = 12F