使用& quot; printf& quot;用于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?
推荐答案
在玩具箱
中修复 printf
很棒.
但如果有人想打印出转换为 hex 的数字(或几乎任何其他合理的 base 从 2
转换为 36
(如果它们会倾斜的话)在带有旧 toybox
(或完全没有 toybox
)的 unrooted 设备上-这是一种使用 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)"
}
这篇关于使用& quot; printf& quot;用于android shell中的十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!