Created
February 12, 2020 23:57
-
-
Save ecoshub/c93556575c33a5b82019fc31a14ddd52 to your computer and use it in GitHub Desktop.
golang into to byte array (as string formation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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