Results 1 to 20 of 20

Thread: Decimal to Binary - Optimising

Hybrid View

  1. #1
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    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)
    {
        
    sbytebin stackalloc sbyte[32]; //32 bytes
        
    sbyteindex bin//duplicate the array pointer and use this as the iterator
        
    sbytestop 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 0mask 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.

  2. #2
    Frenzied Member yrwyddfa's Avatar
    Join Date
    Aug 2001
    Location
    England
    Posts
    1,253

    Re: Decimal to Binary - Optimising

    Yeah the first thing I noticed about Wossy's code is that he straight away went for stack allocations.

    The standard VB6 code uses two heap allocations just to set up the array. You should probably use SafeArrayCreateVectorEx to reduce this to just one heap allocation (heap allocations are expensive)

    There are some (advanced) techniques to get VB to allocate safe array memory on the stack but I won't go into them here (unless you really really want me to)
    "As far as the laws of mathematics refer to reality, they are not certain; and as far as they are certain, they do not refer to reality." - Albert Einstein

    It's turtles! And it's all the way down

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width