Golang : Convert int to byte array([]byte)
Problem :
You need to convert integer variable or constant to byte array ( [] byte ). How to do that?
Solution :
UPDATE: The answer below demonstrates few methods of converting integer variable to []byte
(byte array/slice). The second method should be the answer that you ought to use. Other methods can be useful as well depending on your requirement.
Here you go!
package main
import (
"bytes"
"encoding/binary"
"fmt"
"reflect"
"strconv"
)
func main() {
var intVar = 123
fmt.Println("intVar is : ", intVar)
fmt.Println("intVar type is : ", reflect.TypeOf(intVar))
// depending on what you want to achieve, the first method
// is to split the integer value into individual digit
// i.e 123 to [1,2,3]
// literally ... integer into a byte array of individual digits
var rightMost, tempIntVar int
var byteArray []byte
tempIntVar = intVar
for {
// if use leftMost instead of rightMost, we need to know the length
// of intVar in advance before applying modulo.
// instead of % 10, use % 1e3 , where 3 is the position
// but for simplicity sake and able to handle dynamic intVar length,
// we use rightMost and reverse the order of the slice later.
rightMost = tempIntVar % 10
byteArray = append(byteArray, byte(rightMost)) // convert single digit to byte
// update the tempIntVar, minus the processed rightMost
tempIntVar /= 10
if tempIntVar == 0 {
break
}
}
// need to reverse the order
fixByteArray := []byte{}
for i := range byteArray {
n := byteArray[len(byteArray)-1-i]
fixByteArray = append(fixByteArray, n)
}
//fmt.Println("byteArray : ", byteArray)
fmt.Println("A byte slice for the integer variable.")
fmt.Println("Byte array of integers : ", fixByteArray)
fmt.Printf("Byte array of integers : % x\n", fixByteArray)
fmt.Println("Byte array of integers type is : ", reflect.TypeOf(fixByteArray))
// second method, convert the int directly to []byte
// if you know the machine endian
// for example, LittleEndian
buff := new(bytes.Buffer)
err := binary.Write(buff, binary.LittleEndian, uint16(intVar))
if err != nil {
fmt.Println(err)
}
intByteArray := buff.Bytes()
fmt.Printf("intByteArray : % x\n", intByteArray)
fmt.Println("intByteArray type is : ", reflect.TypeOf(intByteArray))
// verify if 123 translates to 7b correctly
byteI := byte(intVar)
fmt.Printf("%v % x (%T)\n", intVar, byteI, byteI)
// finally, if you just want to
// get the ASCII representation.
// Converting intVar to string first will do the job
intByte := []byte(strconv.Itoa(intVar))
fmt.Println("intByte is : ", intByte)
fmt.Println("intByte in string : ", string(intByte))
fmt.Println("intByte type is : ", reflect.TypeOf(intByte))
}
Output :
intVar is : 123
intVar type is : int
A byte slice for the integer variable.
Byte array of integers : [1 2 3]
Byte array of integers : 01 02 03
Byte array of integers type is : []uint8
intByteArray : 7b 00
intByteArray type is : []uint8
123 7b (uint8)
intByte is : [49 50 51]
intByte in string : 123
intByte type is : []uint8
See also : Golang : convert int to string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.6k Unix/Linux : How to test user agents blocked successfully ?
+7.3k Golang : Handling Yes No Quit query input
+7.8k Golang : Get all countries phone codes
+15.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+23.6k Golang : Use regular expression to validate domain name
+7.5k Golang : Getting Echo framework StartAutoTLS to work
+6.4k Golang : Warp text string by number of characters or runes example
+7.8k Findstr command the Grep equivalent for Windows
+11k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+22.6k Golang : Calculate time different
+7.6k Golang : Scan files for certain pattern and rename part of the files
+13.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error