[英]bash: how to print an integer in hex to a specific length
I am trying to dump the decimal integer values from one file in a hex format. 我正在尝试以十六进制格式从一个文件中转储十进制整数值。 I do have a file with integer values in decimal.
我确实有一个带有十进制整数值的文件。
$ more test.dat_trim
2 9
0 -11
7 -17
14 -1
I am trying to print this integer in hex. 我正在尝试以十六进制打印此整数。 I know also that the integer values are small enough to fit on 2 bytes.
我也知道整数值足够小以适合2个字节。 I want the output to be on 2 bytes.
我希望输出为2个字节。 But then when i am trying:
但是当我尝试时:
declare -i i;for i in $(<test.dat_trim);do printf "%.2x\n" $i; done;
02
09
00
fffffffffffffff5
07
ffffffffffffffef
0e
ffffffffffffffff
Basically printf "%.2x\\n"
it is only working for positive number. 基本上
printf "%.2x\\n"
仅适用于正数。 How can i make it work for negative also? 我怎样才能使它对负面也起作用? Just to clarify what i am expecting: The result should be like this:
只是为了澄清我的期望:结果应该是这样的:
02
09
00
f5
07
ef
0e
ff
meaning that i want for the negative values to be sign extended only on 1 byte. 这意味着我希望负值仅在1个字节上符号扩展。
Printing signed hex values is uncommon, so there is no conversion specifier providing this. 打印带符号的十六进制值并不常见,因此没有转换说明符提供此功能。
You could use the following work around: 您可以使用以下解决方法:
for i in $(<test.dat_trim); do
if [ $i -ge 0 ]; then
printf " 0x%02x\n" $i;
else
printf "%c0x%02x\n" '-' $[$i * -1];
fi
done;
Referrig the update to the question: 将更新提交给问题:
Just replace this line 只需替换此行
printf "%c0x%02x\n" '-' $[$i * -1];
with this 有了这个
printf " 0x%02x\n" $[256 + $i];
This however, only works for the numbers >= -256. 但是,这仅适用于> = -256的数字。
It can be done in awk, that handles negative numbers also: 可以用awk完成,它也可以处理负数:
awk '{printf "0x%x%s0x%x\n", $1, OFS, $2}' OFS='\t' file
0x2 0x9
0x0 0xfffffff5
0x7 0xffffffef
0xe 0xffffffff
金达傻了,但到底:
xargs -a test.dat_trim bash -c 'printf %.2s\\n $(printf %02x\\n $* | rev) | rev' _
您是否尝试过printf(“%04x \\ n”,i)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.