2016-09-21 101 views
1

我需要使用shell腳本轉換符號整型數無符號蒙山shell腳本

例如轉換籤訂INT32號無符號:

convert Input : -256 
Expected output: 4294967040 
+1

那你試試? –

+1

我試過這樣的負數: SIGNED = -256 UNSIGNED = $((0x'printf'%x'$ SIGNED | grep -Eo'。{8} $'')) – Songe

回答

2

這可以幫助你;

#!/bin/bash 
input=$1 
if [[ $input -lt "0" ]]; then 
    output=$((4294967296+$input)) 
else 
    output=$input 
fi 
echo $output 


#signed int32; 
#–2,147,483,648 to 2,147,483,647 
#unsigned int32 
#0 to 4,294,967,295 
1

這裏去,可能不是最快的,但似乎工作

unsigned_to_signed() 
{ 
    local hex=$(printf "0x%x" $(($*))) 
    local unsigned=$(printf "%u" $hex) 
    echo $unsigned 
} 

unsigned_to_signed32() 
{ 
    local hex=$(printf "0x%x" $(($* & 0xFFFFFFFF))) 
    local unsigned=$(printf "%u" $hex) 
    echo $unsigned 
} 

unsigned_to_signed -256 
18446744073709551360 

unsigned_to_signed32 -256 
4294967040 
相關問題