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.


沒有留言:

張貼留言