Rajesh S
Rajesh S

Reputation: 85

Unable to convert my string to hex message

Below has x which is my expected string I am trying to recreate y myself to match my expected string. Basically trying to convert "01" to "\x01" so that I get the same byte when printed.

Now when I print []byte(x) and []byte(y) I want them to be the same but they aren't. Please help me recreate x with "01" as my input.

package main

import (
    "fmt"
)

func main() {
    //Expected string
    x := "\x01"
    //Trying to convert my 01 in string form to same as above - Basically recreate above string again
    y := "\\x" + "01"
    fmt.Println(x)
    fmt.Println(y)
    fmt.Println([]byte(x))
    fmt.Println([]byte(y))
}

Upvotes: 2

Views: 741

Answers (2)

Rajesh S
Rajesh S

Reputation: 85

This is what i wanted - got my issue resolved ! :) Thanks all

import (
    "fmt"
    "encoding/hex"
)

func main() {
    //Expected string
    x := "\x01"
    //Trying to convert my 01 in string form to same as above - Basically recreate above string again
    y,err :=  hex.DecodeString("01")
    if err != nil {
            panic(err)
    }
    fmt.Println(x)
    fmt.Println(y)
    fmt.Println([]byte(x))
    fmt.Println([]byte(y))
}

Upvotes: 5

6502
6502

Reputation: 114519

You cannot build a string from a byte sequence that way... \x01 is an escaping notation processed by the compiler when reading literal strings, you cannot use that processing at runtime.

To build a string with the bytes you want you can simply use

x := string([]byte{1, 2, 3, 4})

Upvotes: 2

Related Questions