简体   繁体   English

如何在保留不可打印字符的同时将十六进制转换为 ASCII

[英]How to convert hex to ASCII while preserving non-printable characters

I've been experiencing some weird issues today while debugging, and I've managed to trace this to something I overlooked at first.我今天在调试时遇到了一些奇怪的问题,我设法将其追溯到我最初忽略的问题。

Take a look at the outputs of these two commands:看看这两个命令的输出:

root@test:~# printf '%X' 10 | xxd -r -p | xxd -p
root@test:~# printf '%X' 43 | xxd -r -p | xxd -p
2b
root@test:~#

The first xxd command converts hex to ASCII.第一个 xxd 命令将十六进制转换为 ASCII。 The second converts ASCII back to hex.第二个将 ASCII 转换回十六进制。 (43 decimal = 2b hex). (43 十进制 = 2b 十六进制)。

Unfortunately, it seems that converting hex to ASCII does not preserve non-printable characters.不幸的是,将十六进制转换为 ASCII 似乎不会保留不可打印的字符。 For example, the raw hex "A" (10 decimal = A hex), somehow gets eaten up by xxd -r -p .例如,原始的十六进制“A”(十进制的 10 = A hex)不知何故被xxd -r -p吃掉了。 Thus, when I perform the inverse operation, I get an empty result.因此,当我执行逆运算时,我得到一个空结果。

What I am trying to do is feed some data into minimodem.我想做的是将一些数据输入 minimodem。 I need to generate Call Waiting Caller ID (FSK), effectively via bit banging.我需要通过 bit banging 有效地生成呼叫等待来电显示 (FSK)。 My bash script has the right bits, but if I do a hexdump, the non-printable characters are missing.我的 bash 脚本具有正确的位,但是如果我执行 hexdump,则缺少不可打印的字符。 Unfortunately, it seem that minimodem only accepts ASCII characters, and I need to feed it raw hex, but it seems that gets eaten up in the conversion.不幸的是,minimodem 似乎只接受 ASCII 字符,我需要给它原始的十六进制,但它似乎在转换中被吃掉了。 Is it possible to preserve these characters somehow?是否有可能以某种方式保留这些字符? I don't see it as any option, so wondering if there's a better way.我不认为这是任何选择,所以想知道是否有更好的方法。

xxd expects two characters per byte. xxd期望每个字节有两个字符。 One A is invalid.一个A是无效的。 Do:做:

printf '%02X' 10 | xxd -r -p | xxd -p

How to convert hex to ASCII while preserving non-printable characters如何在保留不可打印字符的同时将十六进制转换为 ASCII

Use xxd .使用xxd If your input has one character, pad it with an initial 0 .如果您的输入有一个字符,请用初始0填充它。

ASCII does not preserve non-printable characters ASCII 不保留不可打印的字符

It does preserve any bytes, xxd is the common tool to work with any binary data in shell.它确实保留了任何字节, xxd是处理 shell 中任何二进制数据的常用工具。

Is it possible to preserve these characters somehow?是否有可能以某种方式保留这些字符?

Yes - input sequence of two characters per byte to xxd .是 - 每个字节两个字符的输入序列到xxd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM