TraineeGuy
TraineeGuy

Reputation: 91

Go Converting an integer from a string

Recently while taking some algorithm practise at leetcode i came across a solution, i understood everything except the part where the user converts an element in a string to an integer, look at the code below. Hopefully someone can explain this to me. Thanks for replies in advnace.

a := 234
b := strconv.Itoa(a)
c := int(b[0]-48) // why do we subtract 48?

Upvotes: 2

Views: 133

Answers (2)

icza
icza

Reputation: 417592

48 is the code of the '0' character in the ASCII table.

Go stores strings as their UTF-8 byte sequences in memory, which maps characters of the ASCII table one-to-one to their code.

The digits in the ASCII table are listed contiguously, '0' being 48. So if you have a digit in a string, and you subtract 48 from the character's code, you get the digit as a numeric value.

Indexing a string indexes its bytes, and in your case b[0] is the first byte of the b string, which is 2. And '2' - 48 is 2.

For example:

fmt.Println('0' - 48)
fmt.Println('1' - 48)
fmt.Println('2' - 48)
fmt.Println('3' - 48)
fmt.Println('4' - 48)

This outputs (try it on the Go Playground):

0
1
2
3
4

Upvotes: 5

Bradley Weston
Bradley Weston

Reputation: 425

“b” is a string “234”, a string is a slice of rune therefore b[0] is a byte/rune, in this case a value of 50 which is the decimal value of a “2” in ascii. So “c” will be 50-48=2

Upvotes: 2

Related Questions