1

Basically what I'm trying to do is convert a string in the hexidecimal format to a byte and append the byte to a byte slice.

I've tried:

func main() {
    bytes := []byte{0xfc}
    string := "0xe8"
    bytes = append(bytes, string...)
    fmt.Printf("%s", bytes)
}

output:

�0xe8

I know I could just declare a byte variable and append the byte. I need to convert the string into a byte.

Expected output:

��
3
  • 3
    Use strconv.ParseInt Commented Dec 7, 2019 at 10:31
  • Tried: "b, err := strconv.ParseInt(string, 10, 64)" outputed error: "strconv.ParseInt: parsing "0xe8": invalid syntax", Could you provide an example? Commented Dec 7, 2019 at 10:47
  • 2
    Did you read the documentation on strconv.ParseInt, Justin? Commented Dec 7, 2019 at 11:48

1 Answer 1

2

This is work fo me.

func main() {
    bytes := []byte{0xfc}
    str := "0xe8"
    pc, _ := strconv.ParseUint(str, 0, 64)

    bytes = append(bytes, uint8(pc))
    fmt.Printf("%s", bytes)
}

Output:

��

Sign up to request clarification or add additional context in comments.

3 Comments

@Flimzy ok, i changed my post.
@AlexeyBril note that there is no need for the prefix trimming, if you pass in 0 as the base ParseInt and ParseUint will infer the base from the prefix. e.g. strconv.ParseUint("0xe8", 0, 64). From the docs: "If base == 0, the base is implied by the string's prefix: base 2 for "0b", base 8 for "0" or "0o", base 16 for "0x", and base 10 otherwise."
@mkopriva Yes, I agree, this option will be more optimal. Fixed implementation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.