Two's Compliment???

Status
Not open for further replies.

VBguru

New Member
Ok next problem…. I need to know how to get two’s compliment to work with this program. I understand that two’s compliment means that one of the bytes is high for negative numbers (or positive…I cant remember) and opposite for positive numbers.


Which byte is it and how would I implement that into my code?



“Mbasic”

Total Var word
Work var byte
Work2 var byte
OE con P10
SEL con P11


total = 0
High SEL
Low OE
'pause 1
High OE
Dirl = $FF


Main
low OE
'pause 1
Low SEL

work2 = INL
'pause 1
High SEL
Work = INL
'pause 1
High OE

Total = Total + Work + Work2

serout S_out,I57600,["Total = ",sDec Total, 13]

Goto main



**broken link removed**
 
You have a slightly offcenter understanding of twos complement notation.

In unsigned notation 16 bits can represent the numbers from 0 to 65,535. The maximum value of 65,535 is equal to (2^16) - 1

In signed twos complement notation those same 16 bits can represent numbers in the range [-32768,,32767] The following table has some typical values.

Code:
0x7FFF = 32,767
0x0000 = 0
0xFFFF = -1
0x8000 = -32768

To take the twos complement of a number:
1. Take the 1's complement by inverting each bit
2. Add 1 to the result

Examples
Code:
Take the twos complement of 0x7F80
1's complement of 0x7F80 is 0x807F
0x807F + 0x0001 = 0x8080

Take the twos complement of 0x0001
1's complement of 0x0001 is 0xFFFE
0xFFFE + 1 = 0xFFFF

Last point. If your CPU has a subtract instruction you can get the twos complement by subtracting a number from zero
 
Last edited:
Thanks for the info!! Now i can say i understand Two's Compliment

Next question though, I found a problem in my code. I am getting the high byte and the low byte from the chip. I now need to combine them into one 12 bit.... I am guessing that the high byte is 7 bytes (8th being two's compliment) and the low byte is the remaining 4 bytes (5th being two's compliment). Is this correct? And if so how would i combine them?


Thanks
 
You would normally do HighByte*256+LowByte.

How can you have a name like VBguru and not know this stuff?

Mike.
 
I have done quite a bit in visual basic, mostly control apps and a few data base programs, not much of it dealt with any real math other than adding or subtracting. I am new into the micro controllers area and am still learning how they "work". I have mastered the turning of of leds and am venturing into the Unknown....
 
If you want to play in VB with combining negative numbers then,

val("&h" & hex(129) & format(hex(41),"00"))

will combine 129 and 41 and return -32471

Mike.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…