Skip to content

Instantly share code, notes, and snippets.

@ecoshub
Created February 12, 2020 23:57
Show Gist options
  • Save ecoshub/c93556575c33a5b82019fc31a14ddd52 to your computer and use it in GitHub Desktop.
Save ecoshub/c93556575c33a5b82019fc31a14ddd52 to your computer and use it in GitHub Desktop.
golang into to byte array (as string formation)
package main
import "fmt"
func main(){
number := 514235
fmt.Println("original number\t\t\t\t", number)
numArr := IntToByteArray(number)
fmt.Println("number as byte array\t\t", numArr)
fmt.Println("number as string (control).\t", string(numArr))
}
func IntToByteArray(num int) []byte {
if num == 0 {
return []byte{48}
}
old := num
arr := make([]byte, 0, 8)
for num > 0 {
old = num
num = num / 10
arr = append(arr, byte(old-num*10+48))
}
for i := 0; i < len(arr)/2; i++ {
arr[i], arr[len(arr)-i-1] = arr[len(arr)-i-1], arr[i]
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment