Home > Backend Development > Golang > How to Convert a Fixed-Sized Byte Array to a String in Go?

How to Convert a Fixed-Sized Byte Array to a String in Go?

Mary-Kate Olsen
Release: 2024-12-12 13:34:16
Original
306 people have browsed it

How to Convert a Fixed-Sized Byte Array to a String in Go?

Converting Sized Byte Array to String in Go

In Go, it is common to encounter situations where you need to convert a sized byte array to a string. This can arise, for instance, when working with hashed data such as MD5 digests.

Consider the following code snippet:

data := []byte("testing")
var pass string
var b [16]byte
b = md5.Sum(data)
pass = string(b)
Copy after login

Upon executing this code, you will encounter the following error:

cannot convert b (type [16]byte) to type string
Copy after login

The error stems from the fact that the string conversion expects a byte slice ([]byte), but the variable b is declared as a fixed-size array ([16]byte). To resolve this issue and convert the byte array to a string, you can utilize a byte slice derived from the byte array.

The following code demonstrates how to convert a sized byte array to a string correctly:

pass = string(b[:])
Copy after login

By using b[:], you are creating a byte slice that encompasses the entire byte array b. This byte slice can then be converted to a string as expected.

The above is the detailed content of How to Convert a Fixed-Sized Byte Array to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template