使用"printf"用于android shell中的十六进制值 [英] Using "printf" for hex values in android shell
问题描述
我正在将我的shell脚本(相当大的shell脚本)从bash移植到android shell(mksh shell).
I am porting my shell script (quite big shell script) from bash to android shell (mksh shell).
在Android中,printf
的工作方式似乎与其他Linux系统不同.
In Android, printf
does not seem to be working the same way as it works in other Linux systems.
$ cat sample.sh
...
func1()
{
A=100
HEXA=`printf "%04x" ${A}`
echo "A - ${A} HEXA - ${HEXA}"
}
func1
此函数的输出如下.
$ ./sample.sh
A - 100 HEXA - 300000078
它正在打印一个非常奇怪的数字.
It is printing a really weird number.
我从其他帖子和mksh
的联机帮助页中看到,不建议在mksh
中使用printf
.我的Shell脚本很大,正在大量使用它.因此,我想以某种方式处理此问题.我有什么选择来解决这个问题?
I saw from other posts and from the manpage of mksh
that printf
is not recommended to be used in mksh
. My shell script, which is quite big, is using it very heavily. So, I want to handle this somehow. What are my options to handle this?
推荐答案
在toybox
中修复printf
很棒.
但是,如果有人想打印出转换为 hex 的数字(或者,如果可以的话,可以打印几乎所有其他合理的 base 从2
到36
的数字)在具有旧toybox
(或完全没有toybox
)的根植的设备上倾斜-这是一种使用mksh
内置的typeset
来完成此操作的方法:
But in case anyone would like to print out a number converted to hex (or pretty much any other reasonable base from 2
to 36
if they would be so inclined) on an unrooted device with the old toybox
(or no toybox
at all) - here is a way how to do it using typeset
built-in of mksh
:
baseconv(){ typeset -Ui${3:-16} -Z35 x=$1; echo ${x: -${2:-8}};}
func1()
{
A=100
HEXA=$(baseconv $A 4 16)
echo "A - ${A} HEXA - ${HEXA}"
}
或仅针对printf "%04x"
情况设置特定功能:
or just make a specific function for the printf "%04x"
case:
printf04x(){ typeset -Ui16 -Z7 x=$1; echo ${x: -4};}
func1()
{
A=100
echo "A - ${A} HEXA - $(printf04x $A)"
}
这篇关于使用"printf"用于android shell中的十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!