如何在 Bash 中将字符串转换为十六进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34076160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:59:26  来源:igfitidea点击:

How to convert a string into hexadecimal in Bash

arraysbashshellbyte

提问by alecrosic

I've found many posts on StackOverflow which have covered this question in C++, C# and other languages, but none with Shell.

我在 StackOverflow 上发现了很多帖子,这些帖子用 C++、C# 和其他语言讨论了这个问题,但没有一个用 Shell。

Using Bash/Shell, how do I convert a random Stringinto a byte array?

使用 Bash/Shell,如何将随机数String转换为byte array?

I tried:

我试过:

echo "some string" | xxd -r -p

but it didn't work.

但它没有用。

I basically want a byte output - e.g. )?e?GV??vY?Ge?#G

我基本上想要一个字节输出 - 例如 )?e?GV??vY?Ge?#G

回答by

If you want to get the hex values of some string, then this works:

如果您想获取某个字符串的十六进制值,则可以这样做:

$ echo "testing some values"$'7' | xxd
0000000: 7465 7374 696e 6720 736f 6d65 2076 616c  testing some val
0000010: 7565 736f 0a                             ueso.

If you just need the "plain" string:

如果您只需要“普通”字符串:

$ echo "testing some values"$'7' | xxd -p
74657374696e6720736f6d652076616c7565736f0a

If you need to "reverse" an hexstring, you do:

如果您需要“反转”一个十六进制字符串,您可以:

$ echo "74657374696e6720736f6d652076616c7565736f0a" | xxd -r -p
testing some valueso

If what you need is the character representation (not hex), you could do:

如果你需要的是字符表示(不是十六进制),你可以这样做:

$ echo "testing:"$'
$ echo "testing:"$'
string="626c610a"
echo "0: $string" | xxd -r
11\n\bend test' | od -vAn -tax1 t e s t i n g : soh ht nl bs e n d sp 74 65 73 74 69 6e 67 3a 01 09 0a 08 65 6e 64 20 t e s t nl 74 65 73 74 0a
11\n\bend test' | od -vAn -tcx1 t e s t i n g : 001 \t \n \b e n d 74 65 73 74 69 6e 67 3a 01 09 0a 08 65 6e 64 20 t e s t \n 74 65 73 74 0a

Or:

或者:

##代码##

回答by Eugene

Looks like you want to convert hex string to bytes. xxd needs a starting point (since it is used to patch binary files and such)

看起来您想将十六进制字符串转换为字节。xxd 需要一个起点(因为它用于修补二进制文件等)

##代码##

xxd will also silently skip any invalid hex, so check your data if you get empty output.

xxd 还会默默地跳过任何无效的十六进制,因此如果输出为空,请检查您的数据。