|
-
Aug 25th, 2005, 09:04 AM
#13
Re: Decimal to Binary - Optimising
Following JMC's lead I thought it would be fun to do it in C#.
The code is longer but its actually about 5 times faster. No concatenation, no floating point operations. I have used uint's instead of int32's because there is no requirement for converting negative numbers and the largest number containable is twice as large.
I know its in C# but that's the idea, C# lets you use pointers and unmanaged arrays and stuf like that. I just benchmarked this and it runs 1,000,000 (1 million) times in an average time of 0.66 seconds on my old, slow P4 1.8ghz PC.
Whoooooosh! I can't get it to go any faster at the moment, if anyone knows a quicker way then let me know.
PHP Code:
public static unsafe string ToBinary(uint val)
{
sbyte* bin = stackalloc sbyte[32]; //32 bytes
sbyte* index = bin; //duplicate the array pointer and use this as the iterator
sbyte* stop = bin + 32; //stop after 32 bytes in the array
uint mask = 0x80000000; //bit mask
do
{
if((val & mask) != 0)
*index = (sbyte)0x31;
else
*index = (sbyte)0x30;
mask >>= 1;
} while(++index != stop); //let the index catch up the buffer one and then stop
index = bin; //reset pointer
for(mask = 0; mask < 32 ; mask++)
if(*(index++) == 0x31)
break;
return new string(bin, (int)mask, (int)(32 - mask));
}
Last edited by wossname; Aug 25th, 2005 at 10:12 AM.
I don't live here any more.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|