Translate

2015年12月18日 星期五

[C] Pre-define values for array in arbitrary length

For some situations, it is required to pre-define values for array in arbitrary length.
It is related to make use of the pre-processor of limited handling in arbitrary number which I think many experienced programmers have ever suffered from this pain.

Here is a smart method I have ever seen to make use of the binary trick to pre-define values for array in arbitrary length.

#define N    123//length of the array
#define D    4

array[N] =
{
    #if N & 0x1
    D,
    #endif

    #if N & 0x2
    D, D,
    #endif

    #if N & 0x4
    D, D, D, D,
    #endif

    #if N & 0x8
    D, D, D, D, D, D, D, D,
    #endif

    #if N & 0x10
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D
    #endif

    #if N & 0x20
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    #endif

    #if N & 0x40
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    #endif

    #if N & 0x80
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D,
    #endif
}


Mathematically, any positive integer can be expressed as a sum of power of 2 series like below
Therefore, we can make use of above trick to create an array of arbitrary length with pre-defined value.


[Computer Science] Fast Integer Division and Modulus

Sometimes, fast integer division or modulus is required for high speed processing.
Division is normally the most uncomfortable operation for general processors.
Thanks to the math, it is able to convert divisions into bit shift operation by a trick.
Below is a proof of the trick, the idea is inspired from the glorious "Hacker's Delight" 


Since Modulus is a set of operations of division and multiplication like below

a%b = a - (a/b)*b

So, modulus can also take advantages from above trick