Answer the question
In order to leave comments, you need to log in
Because of what, when I convert bytes to a string and back, the bytes are different?
There is the following code:
func main() {
bts := []byte("kek")
btsToStr := fmt.Sprintf("%x", bts)
fmt.Println(btsToStr)
strToBts := []byte(btsToStr)
fmt.Println(fmt.Sprintf("%x", strToBts))
}
func main() {
bts := []byte("kek")
btsToStr := string(bts)
fmt.Println(btsToStr)
strToBts := []byte(btsToStr)
fmt.Println(string(strToBts))
}
Answer the question
In order to leave comments, you need to log in
In the first example, you are not converting bytes to string and back. You convert bytes to their hex codes, and then convert the result back to hex codes again. It is logical that you do not get the same string, because you encode twice and do not decode once.
If you need to put some binary data into something that only supports ASCII text, use base64 instead.
https://go.dev/play/p/NPrAMrsHZje
package main
import (
"encoding/base64"
"fmt"
)
func main() {
srcString := "Привет, тут есть юникод"
fmt.Println("Исходный текст:", srcString)
codedStr := base64.StdEncoding.EncodeToString([]byte(srcString))
fmt.Println("После кодирования:", string(codedStr))
resBytes, err := base64.StdEncoding.DecodeString(codedStr)
if err != nil {
fmt.Println("Ошибка декодирования:", err)
return
}
resString := string(resBytes)
fmt.Println("После декодирования обратно:", resString)
}
Nothing surprising.
The documentation says what %x
Sprintf does.
If you need to make sure the string is valid, then use strings.ToValidUTF8 .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question