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
+9.7k Golang : Convert octal value to string to deal with leading zero problem
+25k Golang : Convert long hexadecimal with strconv.ParseUint example
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+4.9k Golang : Issue HTTP commands to server and port example
+20.2k Nginx + FastCGI + Go Setup.
+19.4k Golang : Set or Add HTTP Request Headers
+11.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+7.4k Golang : Mapping Iban to Dunging alphabets
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+4.5k MariaDB/MySQL : Form select statement or search query with Chinese characters
+13.8k Golang : Reverse IP address for reverse DNS lookup example