![]() |
| ||
| Convert negative decimal to binary Hi, I'm having trouble trying to figure out a code that converts negative decimal numbers to binary, as well as specifying the number of bits. For example. convert -18 using 8 bits. This should come out as 10010010 doing it manually, I think. I'd appreciate the help, thanks. |
| ||
| Re: Convert negative decimal to binary Working with negative numbers in binary you need to use twos complement method. It is a bit confusing to start with (well it was for me). I use it a lot for checksum calculations. Hope this helps. http://www.rsu.edu/faculty/PMacphers...rams/twos.html David |
| ||
| Re: Convert negative decimal to binary you can try Ex-Or ing the positive number with 10000000... it will work for numbers less than 01111111 |
| ||
| Re: Convert negative decimal to binary Check the preample of: http://wiki.python.org/moin/BitwiseOperators |
| ||
| Re: Convert negative decimal to binary Quote:
BITS = 8 |
| ||
| Re: Convert negative decimal to binary So in the manual, it says Quote:
Jeff |
| ||
| Re: Convert negative decimal to binary Oh, nevermind. I thought it was saying something else. All it's saying is that when it performs right-shifts, it rolls in the MSB from the left. (Arithmetic instead of Logical shift) I thought it was saying that it somehow represented negatives as if they had infinite precision, which would be impressive. Jeff |
| ||
| Quote:
This may help you out: Signed Numbers (2 methods) Signed‐and‐Magnitude Leading digit is the sign: 0 = positive; 1 = negative +9 = 00001001 -9 = 10001001 +23 = 00010111 -23 = 10010111 2’s Compliment Decimal to Binary Invert all 0’s and 1’s, and add 1. +9 = 00001001 -9 = 11110110 00000001 + -------- 11110111 +23 = 00010111 -23 = 11101000 00000001 + -------- 11101001 Binary to Decimal Check the sign bit. If the sign bit is 0, number is positive, and you’re done. If it is 1, then number is negative, so invert the bits and add 1. 00001101 = positive number = + 13 (Done) 11110010 negative number 00001100 invert 00000001 + add one -------- 00001101 = - 13 11111111 negative number 00000000 invert 00000001 + add one -------- 00000001 = - 1 10000000 negative number 01111111 invert 00000001 + add one -------- 10000000 = - 128 |
| All times are GMT -4. The time now is 8:06 pm. |
Forum system based on vBulletin Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
©2003 - 2010 DaniWeb® LLC