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
+17.2k Golang : Read binary file into memory
+7.6k Golang : Convert(cast) []byte to io.Reader type
+53.2k Golang : Unmarshal JSON from http response
+22k Find and replace a character in a string in Go
+7k Golang : Randomize letters from a string example
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+5.6k Golang : How to validate ISBN?
+6.3k Golang : Process json data with Jason package
+7.4k Golang : Convert word to its plural form example
+11.2k Golang : Extract part of string with regular expression
+17.6k Golang : Get host name or domain name from IP address