Golang byte to int example

10 May, 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...


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 (

func main() {
	// Type casting
	aByte := byte(144)  // 144
	asInt := int(aByte) // typecast byte to int
	fmt.Println(asInt)  // 144

	// Value of a single char
	aString := "a"            	// String
	asInt2 := int(aString[0]) 	// Byte value of 'a'
					// (character at location 0)
	fmt.Println(asInt2) 		// As a number

	// Incremented value of a single char
	newString := string(aString[0] + 1) 	// Byte value of 'a' +1
	fmt.Println(newString)              	// 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 (

func main() {
	aNumberInByte := []byte("147852")
	aByteToInt, _ := strconv.Atoi(string(aNumberInByte))