I have a short program that converts a few binary numbers into their ASCII equivalents. I tried translating this into go today and found that strconv.Itoa()
doesn't work as I expected.
// translate Computer History Museum t-shirt
// http://i.ebayimg.com/images/g/qksAAOSwaB5XjsI1/s-l300.jpg
package main
import (
"fmt"
"strconv"
)
func main() {
var binaryStrings [3]string
binaryStrings = [3]string{"01000011","01001000","01001101"}
for _,bin := range binaryStrings {
if decimal, err := strconv.ParseInt(bin, 2, 64); err != nil {
fmt.Println(err)
} else {
letter := strconv.Itoa(int(decimal))
fmt.Println(bin, decimal, letter, string(decimal))
}
}
}
which outputs
$ go run chm-tshirt.go
01000011 67 67 C
01001000 72 72 H
01001101 77 77 M
So it seems like string()
is doing what I thought strconv.Itoa()
would do. I was expecting the third column to show what I get in the fourth column. Is this a bug or what am I missing?
strconv.Itoa
formats an integer as a decimal string. Example: strconv.Itoa(65)
and strconv.Itoa('A')
return the string "65"
.
string(intValue)
yields a string containing the UTF-8 representation of the integer. Example: string('A')
and string(65)
evaluate to the string "A"
.
Experience has shown that many people erroneously expect string(intValue)
to return the decimal representation of the integer value. Because this expectation is so common, the Go 1.15 version of go vet
warns about string(intValue)
conversions when the type of the integer value is not rune
or byte
(read details here).