Reputation: 364
I have 10 bit signed binary numbers. I know two shell / bash ways to convert them to decimals yet signedness is not recognized.
1111101010 should be converted to -22 and not 1002.
echo "ibase=2;obase=A;1111101010"| bc
doesn't work. Neither does the following.
echo "$((2#1111101010))"
What can I do?
Edit: Gave wrong expected result; wrong: -220, right: -22.
Upvotes: 3
Views: 1808
Reputation: 96266
Maybe there's a simpler way, but it just simple math:
n=1111101010
sign=${n:0:1}
num=${n:1}
num=$((2#$num))
if [[ $sign == 1 ]]; then
num=$(($num-512))
fi
echo $num
-22 (your example is incorrect).
Upvotes: 7