如何在linux脚本(bash)中用两位数表示十六进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12511762/
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
How to represent hexadecimal number with two digits in linux scripts (bash)
提问by amigal
I have a problem. I must represent each number with exactly 2 digits (i.e. 0F instead of F)
我有个问题。我必须用精确的 2 位数字表示每个数字(即 0F 而不是 F)
my code looks something like that:
1. read number of ascii chars are in an environment variable (using wc -w)
2. converting this number to hexadecimal (using bc).
我的代码看起来像这样:
1. 读取的 ascii 字符数在环境变量中(使用 wc -w)
2. 将此数字转换为十六进制(使用 bc)。
How can I make sure the number I'll get after stage 2 will include a leading 0 (if necessary)
我如何确保在第 2 阶段之后获得的数字将包含前导 0(如有必要)
Thanks, Amigal
谢谢,阿米加尔
回答by unwind
Run it through printf:
运行它printf:
$ printf "%02s" 0xf
0f
If you have the digits of the number only in a variable, say $NUMBER, you can concatenate it with the required 0xprefix directly:
如果您只在变量中包含数字的数字,例如$NUMBER,您可以0x直接将其与所需的前缀连接起来:
$ NUMBER=fea
$ printf "%04x" 0x$NUMBER
0fea
回答by user4815162342
Skip the conversion part in bcand convert the decimal number with the printfcommand:
跳过转换部分,bc用printf命令转换十进制数:
#num=$(... | wc -w)
num=12 # for testing
printf "%02x" $num
0c
If you must convert to hexadecimal for other reasons, then use the 0xprefix to tell printfthat the number is already hexadecimal:
如果由于其他原因必须转换为十六进制,则使用0x前缀告诉printf数字已经是十六进制:
#num=$(... | wc -w | bc ...)
num=c # as obtained from bc
printf "%02x" 0x$num
0c
The %xformat requests formatting the number as hexadecimal, %2xrequests padding to width of two characters, and %02xspecifically requests padding with leading zeros, which is what you want. Refer to the printfmanual (man printfor info coreutils printf) for more details on possible format strings.
该%x格式要求格式为十六进制数,%2x请求填充,以两个字符的宽度,并%02x特别要求填充带前导零,这是你想要的。有关可能的格式字符串的更多详细信息,请参阅printf手册(man printf或info coreutils printf)。

