Using “printf” for hex values in android shell

后端 未结 2 1542
心在旅途
心在旅途 2021-01-23 11:47

I am porting my shell script (quite big shell script) from bash to android shell (mksh shell).

In Android, printf does not seem to be working the same way a

2条回答
  •  爱一瞬间的悲伤
    2021-01-23 12:04

    Fixing printf in toybox is great.

    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}"
    }
    

    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)"
    }
    

提交回复
热议问题