How to convert Hex to ASCII

妖精的绣舞 提交于 2019-12-22 06:24:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37506631/how-to-convert-hex-to-ascii

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!