PiEnthusiast
PiEnthusiast

Reputation: 364

Convert signed 10 bit binary numbers to decimal?

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

Answers (1)

Karoly Horvath
Karoly Horvath

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

Related Questions