美文网首页
Linux Shell 有符号和无符号数互转

Linux Shell 有符号和无符号数互转

作者: 云石畅想 | 来源:发表于2019-07-09 21:12 被阅读0次

    工作中经常会遇到有符号到无符号的转化,写个c程序没必要,就用shell几行就好,int64和unsigned int64之间的:

    signed_to_unsigned()
    {
      local hex=$(printf "0x%x" $(( $* )))
      local unsigned=$(printf "%u" $hex )
      echo $unsigned
    }
    
    unsigned_to_signed()
    {
      echo $(( $* ))
    }
    
    
    
    a=-1000
    echo "a:" $a ", unsigned value:" `signed_to_unsigned $a`
    
    b=18446744073709550616
    echo "b:" $b ", signed value:" `unsigned_to_signed $b`
    

    输出结果:

    $ sh unsigned_to_signed.sh  
    a: -1000 , unsigned value: 18446744073709550616
    b: 18446744073709550616 , signed value: -1000
    

    转载请注明来自KyAn0: KyAn0的博客

    相关文章

      网友评论

          本文标题:Linux Shell 有符号和无符号数互转

          本文链接:https://www.haomeiwen.com/subject/nbzfkctx.html