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
+11.3k Golang : Handle API query by curl with Gorilla Queries example
+10.5k Android Studio : Checkbox for user to select options example
+4.7k JQuery : Calling a function inside Jquery(document) block
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+22.2k Golang : How to read JPG(JPEG), GIF and PNG files ?
+13.3k Golang : reCAPTCHA example
+9.6k Golang : Get current, epoch time and display by year, month and day
+13.2k Golang : How to get year, month and day?
+7.2k Golang : Check to see if *File is a file or directory
+9.3k Golang : How to extract video or image files from html source code
+11.4k Golang : Calculations using complex numbers example
+10.3k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?