I'm writing a go program to convert hex to int, binary and ascii. The int and binary worked fine but ascii is causing issues. If the input text is shorter than 2 characters it works fine, but anything longer causes malformed text to appear. My code is as follows:
package main
import "fmt"
import "strconv"
func main() {
// get input as string
fmt.Print("Enter hex to convert: ")
var input_hex string = ""
fmt.Scanln(&input_hex)
// convert hex to int and print outputs
if i, err := strconv.ParseInt(input_hex, 16, 0); err != nil {
fmt.Println(err)
} else {
// int
fmt.Print("Integer = ")
fmt.Println(i)
// ascii
fmt.Print("Ascii = ")
fmt.Printf("%c", i)
fmt.Println("")
// bin
fmt.Print("Binary = ")
fmt.Printf("%b", i)
fmt.Println("\n")
}
}
An example of some output when entering hex '73616d706c65':
Enter hex to convert: 73616d706c65
Integer = 126862285106277
Ascii = �
Binary = 11100110110000101101101011100000110110001100101
I've done lots of searching and have seen some documentation in regards to 'runes' but i'm unsure as to how this works. Is there a built-in hex encode/decode library that can be used to accomplish this?
There's a hex
package in the standard library that can decode hex into bytes. If it's valid utf-8 (which all ASCII is), you can display it as a string.
Here it is in action:
package main
import (
"encoding/hex"
"fmt"
)
func main() {
a := "73616d706c65"
bs, err := hex.DecodeString(a)
if err != nil {
panic(err)
}
fmt.Println(string(bs))
}
The output is "sample", which you can see on the playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With