bash ascii 到十六进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12847328/
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
bash ascii to hex
提问by user1739261
was wondering if anyone could help me with converting ascii to hex in bash. Example code:
想知道是否有人可以帮助我在 bash 中将 ascii 转换为十六进制。示例代码:
#!/bin/bash
STR = "hello"
#Convert to hex
HEXVAL = $STR #(in hex here?)
I want hexval to have the value: 68656C6C6F (hello in hex)
我希望 hexval 具有以下值:68656C6C6F(你好,十六进制)
回答by John Kugelman
$ STR="hello"
$ HEXVAL=$(xxd -pu <<< "$STR")
$ echo "$HEXVAL"
6C6C6568A6F
Or:
或者:
$ HEXVAL=$(hexdump -e '"%X"' <<< "$STR")
$ echo "$HEXVAL"
6C6C6568A6F
Careful with the '"%X"'
; it has both single quotes and double quotes.
小心'"%X"'
; 它有单引号和双引号。
回答by mrchampe
You have several options
你有几个选择
$ printf hello | xxd
0000000: 6865 6c6c 6f hello
See also: Ascii/Hex convert in bash
另请参阅: bash 中的 Ascii/Hex 转换
回答by blogresponder
here's a one liner (a little complex but works fine):
这是一个单班轮(有点复杂但工作正常):
#!/bin/bash
echo '0x'"`echo | hexdump -vC | awk 'BEGIN {IFS="\t"} {=""; print }' | awk '{sub(/\|.*/,"")}1' | tr -d '\n' | tr -d ' '`" | rev | cut -c 3- | rev
回答by makarevs
Pure BASH convertor of string to printable hexadecimal sequence and back
字符串到可打印的十六进制序列并返回的纯 BASH 转换器
str2hex_echo() {
# USAGE: hex_repr=$(str2hex_echo "ABC")
# returns "0x410x420x43"
local str=${1:-""}
local fmt="0x%x"
local chr
local -i i
for i in `seq 0 $((${#str}-1))`; do
chr=${str:i:1}
printf "${fmt}" "'${chr}"
done
}
hex2str_echo() {
# USAGE: ASCII_repr=$(hex2str_echo "0x410x420x43")
# returns "ABC"
echo -en "'${1:-""//0x/\x}'"
}
EXPLANATION
解释
ASCII->hex: The secret sauce of efficient conversion from character to its underlying ASCII code is feature in printf
that, with non-string format specifiers, takes leading character being a single or double quotation mark as an order to produce the underlying ASCII code of the next symbol. This behavior is documented in GNU BASH reference, but is also exposed in details together with many other other wonderful utilities in Greg's (also known as GreyCat's) wiki page BashFAQ/071dedicated to char-ASCII conversions.
ASCII->hex:从字符到其底层 ASCII 码高效转换的秘诀printf
在于,使用非字符串格式说明符,将前导字符作为单引号或双引号作为顺序生成底层 ASCII 码下一个符号。此行为记录在GNU BASH 参考 中,但也与 Greg(也称为GreyCat的)wiki 页面BashFAQ/071 中专门用于 char-ASCII 转换的许多其他精彩实用程序一起详细公开。
回答by anthony
xxd -p -u <<< "$STR" | sed 's/\(..\)/0x&, /g; s/, $//;'
0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x0A
0x68、0x65、0x6C、0x6C、0x6F、0x0A