| View previous topic :: View next topic |
| Author |
Message |
infogulch
Joined: 27 Mar 2008 Posts: 649
|
Posted: Wed Feb 03, 2010 9:46 pm Post subject: Binary and Decimal conversion |
|
|
I decided to create a couple functions for converting decimal numbers to binary and vica-versa.
Here they are: | Code: | 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) | Code: | 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. _________________ Scripts - License |
|
| Back to top |
|
 |
pkutter
Joined: 18 Mar 2009 Posts: 17 Location: Minnesota, USA
|
Posted: Wed Feb 03, 2010 11:55 pm Post subject: Works great! |
|
|
| 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. |
|
| Back to top |
|
 |
Laszlo
Joined: 14 Feb 2005 Posts: 4710 Location: Boulder, CO
|
Posted: Thu Feb 04, 2010 12:01 am Post subject: |
|
|
| 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. |
|
| Back to top |
|
 |
infogulch
Joined: 27 Mar 2008 Posts: 649
|
Posted: Thu Feb 04, 2010 12:21 am Post subject: |
|
|
Thanks Laszlo, pkutter.
Yes, I just realized this breaks when dealing with negative numbers.
pkutter: for hex numbers try SetFormat _________________ Scripts - License |
|
| Back to top |
|
 |
pkutter
Joined: 18 Mar 2009 Posts: 17 Location: Minnesota, USA
|
Posted: Thu Feb 04, 2010 5:18 am Post subject: |
|
|
Ah, yes.... I had seen that once before... sorry.  |
|
| Back to top |
|
 |
|