Two's Compliment

Everything else that doesn't fall into one of the other PB categories.
Killswitch
Enthusiast
Enthusiast
Posts: 731
Joined: Wed Apr 21, 2004 7:12 pm

Two's Compliment

Post by Killswitch »

Does any one here know how to perform Two's Compliment on a binary number in PB?

Thanks,

Killswitch
Last edited by Killswitch on Wed Oct 19, 2005 9:39 pm, edited 1 time in total.
~I see one problem with your reasoning: the fact is thats not a chicken~
Kale
PureBasic Expert
PureBasic Expert
Posts: 3000
Joined: Fri Apr 25, 2003 6:03 pm
Location: Lincoln, UK
Contact:

Post by Kale »

--Kale

Image
Killswitch
Enthusiast
Enthusiast
Posts: 731
Joined: Wed Apr 21, 2004 7:12 pm

Post 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.
~I see one problem with your reasoning: the fact is thats not a chicken~
Kale
PureBasic Expert
PureBasic Expert
Posts: 3000
Joined: Fri Apr 25, 2003 6:03 pm
Location: Lincoln, UK
Contact:

Post by Kale »

Code: Select all

Var.b = %01101011
Debug Var

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

Image
Killswitch
Enthusiast
Enthusiast
Posts: 731
Joined: Wed Apr 21, 2004 7:12 pm

Post 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?
~I see one problem with your reasoning: the fact is thats not a chicken~
User avatar
Droopy
Enthusiast
Enthusiast
Posts: 658
Joined: Thu Sep 16, 2004 9:50 pm
Location: France
Contact:

Post 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 
Kale
PureBasic Expert
PureBasic Expert
Posts: 3000
Joined: Fri Apr 25, 2003 6:03 pm
Location: Lincoln, UK
Contact:

Post 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)
--Kale

Image
Post Reply