Thursday, December 17, 2020 • 2 minutes to read

Golang2020to-the-pointconversiongolang

## Decimal Number System

Decimal number system is the standard system for denoting integers and non-integers numbers.
This is also known as base 10 number system.

``````0 1 2 3 4 5 6 7 8 9
``````

Hexadecimal (mostly used as hex) number system use 16 symbols. It is known as base 16 number system, where 10 symbols are same as decimal and value greater than 9 represent as A=10, B=11, C=12, D=13, E=14, F=15.

``````0 1 2 3 4 5 6 7 8 9 A B C D E F
``````

Golang package `strconv` provides `ParseInt` and `ParseUint` to convert the string to the number in the respective base. Hexadecimal numbers are commonly use `0x` or `0X` in front of the number. It is only to avoid confusion.

Syntax

``````1func ParseInt(s string, base int, bitSize int) (i int64, err error)
``````
`````` 1package main
2
3import (
4	"fmt"
5	"strconv"
6)
7
8func main() {
9	hexa := "F1"
10
11	decimal, err := strconv.ParseInt(hexa, 16, 32)
12
13	if err != nil {
14		fmt.Println(err)
15	}
16
17	fmt.Printf("Hexadecimal %s (base16) = Decimal %v (base10)", hexa, decimal)
18}
``````

Output

``````1Hexadecimal F1 (base16) = Decimal 241 (base10)
``````

The `ParseUint` is same as `ParseInt` but it takes only unsigned integers. To remove the `0x` or `0X` from the hex number, you can use slices.

``````1hexa := "0xfc"
2hexa = hexa[2:]
``````

The same `strconv` package provides `FormatInt` and `FormatUint` to convert the decimal number to a respective base number.

`````` 1package main
2
3import (
4	"fmt"
5	"strconv"
6)
7
8func main() {
9	var decimal int64 = 252
10
11	hexa := strconv.FormatInt(decimal, 16)
12
13	fmt.Printf("Decimal %v (base10) = Hexadecimal %s (base16)", decimal, hexa)
14}
``````

The `FormatUint` is same as `FormatInt` but it takes only unsigned integers.

For negative numbers use `-` minus sign.

Golang2020to-the-pointconversiongolang

PreviousCheck if a character is a number in Golang

NextString Split in Golang