如何将十六进制转换为ASCII

编程入门 行业动态 更新时间:2024-10-27 16:32:52
本文介绍了如何将十六进制转换为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

本文发布于:2023-10-27 18:34:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   十六进制   ASCII

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!