Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Binary and Decimal conversion


  • Please log in to reply
4 replies to this topic
infogulch
  • Moderators
  • 717 posts
  • Last active: Jul 31 2014 08:27 PM
  • Joined: 27 Mar 2008
I decided to create a couple functions for converting decimal numbers to binary and vica-versa.

Here they are:
Bin(x){
	while x
		r:=1&x r,x>>=1
	return r
}
Dec(x){
	b:=StrLen(x),r:=0
	loop,parse,x
		r|=A_LoopField<<--b
	return r
}
I tried several different versions, and these are the fastest (and shortest) I could come up with.

If you're interested, I first created some one-liners that do the same thing. Though I must warn that they are both slower and longer: (longer in the number of non-whitespace characters)
Bin(x){
	return (x>>1 ? Bin(x>>1):"")x&1 
}
Dec(x){
	return (StrLen(x)>1 ? Dec(SubStr(x,1,-1))<<1:0)|SubStr(x,0)
}
The fact that they are significantly slower perplexes me. Perhaps it's the overhead of calling itself many times.

pkutter
  • Members
  • 17 posts
  • Last active: Jul 28 2010 09:18 PM
  • Joined: 18 Mar 2009
Thanks infogulch, I was looking for something similar about a year ago. I don't remember why I needed it any more though... I think I was working on subnet calculations. Any chance of doing a hex conversion as well? I imagine that may be a little more difficult with the 6 extra characters though. Anyway, great job.

Laszlo
  • Moderators
  • 4713 posts
  • Last active: Mar 31 2012 03:17 AM
  • Joined: 14 Feb 2005
Nice! General base conversion is even faster with dll calls. Converting negative numbers to binary is a bit tricky without specifying the length, but there are many pure AHK solutions out there.

infogulch
  • Moderators
  • 717 posts
  • Last active: Jul 31 2014 08:27 PM
  • Joined: 27 Mar 2008
Thanks Laszlo, pkutter. :)

Yes, I just realized this breaks when dealing with negative numbers.

pkutter: for hex numbers try SetFormat

pkutter
  • Members
  • 17 posts
  • Last active: Jul 28 2010 09:18 PM
  • Joined: 18 Mar 2009
Ah, yes.... I had seen that once before... sorry. :oops: