Menu Close

AppendInt function of strconv package in go

In this article, we are going to learn about AppendInt function of strconv package in go with code and example.

The AppendInt function of strconv package in go allows to append an integer value to a byte slice which efficiently converting the integer to its string representation in the process.

Function prototype:

func AppendInt(dst []byte, i int64, base int) []byte

The function takes three arguments:

  1. dst: The destination byte slice to which the integer value will be appended.
  2. i: The integer value to be appended.
  3. base: The base (radix) in which the integer value should be represented.

The function returns a new byte slice, which is the result of appending the integer value to the destination byte slice.

Example 1:

package main


import (

	"fmt"

	"strconv"

)


func main() {

	byteSlice := []byte("The value is: ")

	num := int64(42)

	base := 10


	result := strconv.AppendInt(byteSlice, num, base)

	fmt.Println(string(result)) // Output: The value is: 42

}

In the example above, we start with a byte slice containing the string “The value is: “. We then append the integer value 42 to the byte slice, using base 10 representation.

Output:

The value is: 42

Example 2:

The AppendInt function allows you to represent the appended integer in different bases, ranging from 2 (binary) to 36 (using alphanumeric characters).

package main


import (

	"fmt"

	"strconv"

)


func main() {

	byteSlice := []byte("The binary value is: ")

	num := int64(42)


	result := strconv.AppendInt(byteSlice, num, 2)

	fmt.Println(string(result)) // Output: The binary value is: 101010


	byteSlice = []byte("The hexadecimal value is: ")

	result = strconv.AppendInt(byteSlice, num, 16)

	fmt.Println(string(result)) // Output: The hexadecimal value is: 2a

}

In this example, we append the integer value 42 to two different byte slices, representing the value in binary (base 2) and hexadecimal (base 16).

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-strconv-package-in-go/

References:

https://golang.org/pkg/

Posted in golang, packages, strconv

Leave a Reply

Your email address will not be published. Required fields are marked *