I need to create a string consisting of a single byte corresponding to an integer of at most 255. It is acceptable that the string is not valid Unicode.
Code:
import ("fmt""strings")func main() { n := 255 s := "" s += string(byte(n)) fmt.Printf("Method 1: %x\n", s) sb := strings.Builder{} sb.WriteByte(byte(n)) fmt.Printf("Method 2: %x\n", sb.String())}
Output:
Method 1: c3bfMethod 2: ff
In the first method, Go appends ÿ
to the string because 255 is the code point for this Unicode character.
In the second method, Go appends the 0xff
(255) byte to the string. This is the desired result, but is there a simpler way to accomplish this without needing to import the strings
package? Why does Go interpret the byte as a Unicode code point in the first method?