Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: How to 2s complement

1 view
Skip to first unread message

Jonathan Wood

unread,
Jun 29, 2004, 1:26:32 PM6/29/04
to
You can obtain the two's complement of a value by subtracting the value from
0.

--
Jonathan Wood
SoftCircuits
http://www.softcircuits.com
Available for consulting: http://www.softcircuits.com/jwood/resume.htm

"krollenhagen" <v...@nospam.rollenhagen.us> wrote in message
news:17EE96A9-8EEE-4832...@microsoft.com...
> Hello-
>
> I am trying to take the 2s complement of a number. I have converted the
number into a binary string and then negated the string using if..then
statements. I can then convert this into a decimal value easily enough.
>
> I am wondering if there is an easier way to do this?
>
> Just wondering,
>
> Keith


Tony Proctor

unread,
Jun 29, 2004, 1:29:13 PM6/29/04
to
You don't need to do all that Keith.

"Two's complement" is simply numeric negation. For instance: lX2Complement
= -lX (where lX might be a Long variable)

Also,"One's completion" is simply bitwise inversion. For instance :
lX1Complement = Not lX

Tony Proctor

Steve Garman

unread,
Jun 29, 2004, 1:42:21 PM6/29/04
to
krollenhagen wrote:
> Hello-
>
> I am trying to take the 2s complement of a number. I have converted the number into a binary string and then negated the string using if..then statements. I can then convert this into a decimal value easily enough.
>
> I am wondering if there is an easier way to do this?
>
> Just wondering,
>
> Keith

Maybe I'm being really dim, but if you're starting with a decimal number
and ending with a decimal number, are you trying to do anything
different than multiply the number by (-1) ?

Perhaps your problem is something to do with the length of the number in
bits.

If you need to manipulate the bits directly, look at the Not operator

--
Steve Garman

krollenhagen

unread,
Jun 29, 2004, 1:48:02 PM6/29/04
to
Thank you.

Doug

unread,
Jun 29, 2004, 1:51:34 PM6/29/04
to
I don't know if this applies to you but here's a little function I wrote
years ago to to take the 2's complement of the Mod 256 sum of the data bytes
in the string if interest....

Private Function CheckSum(TheString As String, TheLength As Integer) As
String

Dim TempCheckSum As Integer
Dim i As Integer

For i = 1 To TheLength
TempCheckSum = (TempCheckSum + Asc(Mid$(TheString, i, 1))) And &HFF
Next i
CheckSum = Chr$((-TempCheckSum) And &HFF)

End Function

I seem to remember returning a string since I was just appending it the
TheString.

krollenhagen

unread,
Jun 29, 2004, 4:10:03 PM6/29/04
to
I am calculating the BCC error correction byte and having to tack that on to the end of the string that I am sending out on the serial port.

Thanks for all your help. I got it working.

Keith

0 new messages