Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert rune to int?

In the following code, I iterate over a string rune by rune, but I'll actually need an int to perform some checksum calculation. Do I really need to encode the rune into a []byte, then convert it to a string and then use Atoi to get an int out of the rune? Is this the idiomatic way to do it?

// The string `s` only contains digits. var factor int for i, c := range s[:12] {     if i % 2 == 0 {         factor = 1     } else {         factor = 3     }     buf := make([]byte, 1)     _ = utf8.EncodeRune(buf, c)     value, _ := strconv.Atoi(string(buf))     sum += value * factor } 

On the playground: http://play.golang.org/p/noWDYjn5rJ

like image 744
miku Avatar asked Jan 24 '14 00:01

miku


1 Answers

The problem is simpler than it looks. You convert a rune value to an int value with int(r). But your code implies you want the integer value out of the ASCII (or UTF-8) representation of the digit, which you can trivially get with r - '0' as a rune, or int(r - '0') as an int. Be aware that out-of-range runes will corrupt that logic.

like image 100
Gustavo Niemeyer Avatar answered Oct 08 '22 10:10

Gustavo Niemeyer