Hexadecimal Literals in Golang

Golang | Hexadecimal: In this tutorial, we are going to learn about the hexadecimal literals, how to use hexadecimal values in Go Language?
Submitted by IncludeHelp, on April 07, 2021

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).

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




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.