Convert signed 10 bit binary numbers to decimal?
Asked Answered
E

1

3

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.

Eighteenth answered 24/1, 2014 at 17:36 Comment(3)
strip the leading digit, do some math.Brenna
also, is your example correct? it doesn't look -220 to me.Brenna
Sorry, I skipped another calculation 1111101010 is -22.Eighteenth
B
7

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).

Brenna answered 24/1, 2014 at 17:45 Comment(4)
My answer was based on the expected output (not the provided input). Your answer is better, so I deleted mine (and up-voted yours).Lund
1002 - 1024 = -2.2 That's it, simple. Thanks.Eighteenth
Also, I should add, to get to my expected result the signifying bit must either remain or 512 rather than 1024 needs to be subtracted.Eighteenth
@PiEnthusiast: that was fixed long before you posted your comment.Brenna

© 2022 - 2024 — McMap. All rights reserved.