How can I get the correct value from string to byte conversion?

Issue

I need to convert strings to byte slices, I use the function []byte(string), but when the string has the letter ñ or some letter with an accent I get a different value than expected.

fmt.Println([]byte("áéíóúñÁÉÍÓÚÑ"))

Expected result: [ 160 130 161 162 163 181 144 214 224 233 ]

Obtained result: [195 161 195 169 195 173 195 179 195 186 195 177 195 129 195 137 195 141 195 147 195 154 195 145]

So when I convert to string the obtained value I get ├í├®├¡├│├║├▒├ü├ë├ì├ô├Ü├æ instead of áéíóúñÁÉÍÓÚÑ

How can I get the right values?

Solution

Several issues here. First, you give this expected result:

[ 160 130 161 162 163 181 144 214 224 233 ]

but you left out the ñ and Ñ, so expected result should be:

[160 130 161 162 163 164 181 144 214 224 233 165]

Second, this page you link to [1] says it is code page 437, but it’s actually
code page 850. You can see 850 listed under "other related encodings" [2].
Here is a working example [3]:

package main

import (
   "fmt"
   "golang.org/x/text/encoding/charmap"
)

func main() {
   b := []byte("áéíóúñÁÉÍÓÚÑ")
   c, e := charmap.CodePage850.NewEncoder().Bytes(b)
   if e != nil {
      panic(e)
   }
   fmt.Println(c)
}
  1. https://theasciicode.com.ar
  2. https://wikipedia.org/wiki/Code_page_437
  3. https://pkg.go.dev/golang.org/x/text/encoding/charmap

Answered By – Zombo

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.