Reputation: 4419
How do I obtain the alphabet value from the hex value in Go?
package main
import (
"encoding/hex"
"fmt"
)
func main() {
a := []byte{0x61}
c := hex.Dump(a)
fmt.Println(c,a)
}
http://play.golang.org/p/7iAs2kKw5v
Upvotes: 2
Views: 1129
Reputation: 417777
Your question is a little misleading.
Based on your question what you really want is convert a byte
value or a []byte
(byte slice) to a string
or character (which is more or less a rune
in Go).
Henceforth I will separate the single byte
value from the []byte
using these variables:
b := byte(0x61)
bs := []byte{b}
To convert it to a string
, you can simply use a conversion which is the cleanest and most simple:
s := string(bs)
If you want it as a "character", you can convert it to a rune
:
r := rune(b)
Another solution is using fmt.Printf()
as mentioned in VonC's answer and using the %s
verb which is:
%s the uninterpreted bytes of the string or slice
You might want to take a look at these alternatives:
%c the character represented by the corresponding Unicode code point
%q a single-quoted character literal safely escaped with Go syntax.
%q
accepts both a byte
, []byte
and rune
.
See this litte example to demonstrate these (try it on the Go Playground):
b := byte(0x61)
bs := []byte{b}
fmt.Printf("%s\n", bs)
fmt.Printf("%c\n", b)
fmt.Println(string(bs))
fmt.Printf("%q\n", bs)
fmt.Printf("%q\n", b)
fmt.Printf("%q\n", rune(b))
Output:
a
a
a
"a"
'a'
'a'
If you need the result as a string
, you can use the fmt.Sprintf()
variant mentioned in satran's answer like this:
s := fmt.Sprintf("%s", bs)
But it's easier to just use the string
conversion (string(bs)
).
Upvotes: 1
Reputation: 1232
If you just want the string you can you fmt.Sprintf
.
package main
import (
"fmt"
)
func main() {
a := []byte{0x61}
c := fmt.Sprintf("%s", a)
fmt.Println(c)
}
Upvotes: 0
Reputation: 1324827
You could use a fmt.Printf()
format (example):
func main() {
a := []byte{0x61}
c := hex.Dump(a)
fmt.Printf("'%+v' -- '%s'\n", c, a)
}
Output:
'00000000 61 |a|
' -- 'a'
The %s
format is enough to convert the 0x61
in 'a
'.
Upvotes: 3