Page 1 of 1

Two's Compliment

Posted: Wed Oct 19, 2005 9:25 pm
by Killswitch
Does any one here know how to perform Two's Compliment on a binary number in PB?

Thanks,

Killswitch

Posted: Wed Oct 19, 2005 9:31 pm
by Kale

Posted: Wed Oct 19, 2005 9:38 pm
by Killswitch
I've already read that thread, it does explain how to do two's compliment (invert the bits and add one) but it doesn't give any code - and thats what I'm really after.

Posted: Wed Oct 19, 2005 9:56 pm
by Kale

Code: Select all

Var.b = %01101011
Debug Var

Var = ~Var + 1
Debug Var
Something like that?

Posted: Wed Oct 19, 2005 10:03 pm
by Killswitch
Yep, something exactly like that. The only problem is that I'll be reading the binary value from a string - how can I convert that to a byte?

Posted: Wed Oct 19, 2005 10:33 pm
by Droopy
Try this : ( Author : fweil )

Code: Select all

ProcedureDLL.l Bin2Dec(BinaryStringNumber.s) 
  *t.OneByte = @BinaryStringNumber 
  Result.l = 0 
  While *t\a <> 0 
    Result = (Result << 1) + (*t\a - 48) 
    *t + 1 
  Wend 
  ProcedureReturn Result 
EndProcedure 

Posted: Thu Oct 20, 2005 12:28 am
by Kale
Droopy wrote:Try this : ( Author : fweil )
Had a little trouble with this procedure so i've written another one based upon it, it could do with some validation on the binary string though! :twisted: ...but you get the idea! :P

Code: Select all


Procedure.l ValB(String.s)
	Protected Result.l
	Protected Pointer.l
	Pointer.l = @String
	For x = 1 To Len(String)
		Result = (Result << 1) + (PeekB(Pointer) - 48)
		Pointer + 1
	Next x
	ProcedureReturn Result
EndProcedure

TestBinary1.b = %01101011
TestBinary2.w = %0110101100111111
TestBinary3.l = %01101011011111110110111100110011

Debug "Binary Numbers:"
Debug TestBinary1
Debug TestBinary2
Debug TestBinary3
Debug ""

TestString1.s = "01101011"
TestString2.s = "0110101100111111"
TestString3.s = "01101011011111110110111100110011"

Debug "Binary Numbers From Strings:"
Debug ValB(TestString1)
Debug ValB(TestString2)
Debug ValB(TestString3)