Golang byte to int example
May 10, 2016
In Golang there isn't a native function to convert a character number (!= int number) to int.
An int in bytes is the normal sequence of 0-9 normally, but when you are dealing with number characters, they start of at number 48 (in the ASCII table)
So a character 0 is 48 in bytes, 1 is 49, 2 is 50, and so on...
Update*
I've noticed that the title is quite unclear, byte to int is simply done by type casting, do know that a single byte can only be at most 255, any bigger value will overflow it.
package main
import (
"fmt"
)
func main() {
// Type conversion
aByte := byte(144) // 144
asInt := int(aByte) // converse byte to int
fmt.Println(asInt) // 144
// Value of a single char
aString := "a" // String
asInt2 := int(aString[0]) // Byte value of 'a'
// (rune at location 0)
fmt.Println(asInt2) // As a number
// Incremented value of a single char
newString := string(aString[0] + 1) // Value of rune 'a' + 1
fmt.Println(newString) // prints "b"
}
Output:
144
97
b
Success: process exited with code 0.
ASCII byte numbers to int
An nice way to deal with it would be bitshifting -48 to get a real integer, or just do the lazy work around by converting it to a string first, and then to an integer with Atoi().Â
package main
import (
"fmt"
"strconv"
)
func main() {
aNumberInByte := []byte("147852")
aByteToInt, _ := strconv.Atoi(string(aNumberInByte))
fmt.Println(aByteToInt)
}
Â
Comments
Tags