如何将十六进制转换为ASCII [英] How to convert Hex to ASCII

查看:1087
本文介绍了如何将十六进制转换为ASCII的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个go程序,将十六进制转换为int,binary和ascii. int和二进制文件工作正常,但是ascii引起了问题.如果输入的文本少于2个字符,则可以正常工作,但是如果输入的文本超过2个字符,则会导致出现格式错误的文本.我的代码如下:

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")
    }

}

输入十六进制" 73616d706c65 "时的一些输出示例:

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?

推荐答案

标准库中有一个hex包,可以将十六进制解码为字节.如果它是有效的utf-8(所有ASCII都是有效的),则可以将其显示为字符串.

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.

这里正在起作用:

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.

这篇关于如何将十六进制转换为ASCII的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆