E
E
egorggegor2022-02-01 22:27:05
go
egorggegor, 2022-02-01 22:27:05

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))
}

It will output:
6b656b
366236353662

Why is this happening? In theory, they should be the same bytes, but it seems that sprintf somehow changes the data.

At the same time, the following code:
func main() {
  bts := []byte("kek")
  btsToStr := string(bts)
  fmt.Println(btsToStr)

  strToBts := []byte(btsToStr)
  fmt.Println(string(strToBts))
}

Output :
kek
kek

Why is this happening?
The second example does not suit me, because if I give it strange characters that cannot be read by UTF8, then my database will not get into the database.
Can you please tell me how can I normally convert from bytes to a string and vice versa?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2022-02-02
@egorggegor

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)
}

R
Roman Mirilaczvili, 2022-02-02
@2ord

Nothing surprising.
The documentation says what %xSprintf 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 question

Ask a Question

731 491 924 answers to any question