使用联合和匿名结构的C模数

时间:2012-07-13 08:11:27

标签: c modulus unions anonymous-struct

我在工会中使用匿名结构来快速获得%b。

你知道如何获得%b而不使用2的幂为b。

包括列表:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

和工会声明:

//C99
//my first program to test rand() for any periodicity
union //for array indexing without modulus operator
{
unsigned int counter; //32 bit on my computer
struct
{
    unsigned int lsb:16; //16 bit 
    unsigned int msb:16; //16 bit   
};
struct 
{
    unsigned int bit[32];
};
} modulo;

union // for rand()%256
{
unsigned int randoom; //from rand() 
struct
{
unsigned int lsb:5;//equivalent to rand()%32 without any calculations
unsigned int msb:27;
};
}random_modulus;

这里的主要功能是:

int main()
{
srand(time(0));

modulo.counter=0;//init of for-loop counter

// i am takin (counter%65536) for my array index which is modulus.lsb
unsigned int array_1[65536]; 
float array_mean=0,delta_square=0;
clock_t clock_refe;


//taking counter%65536 using lsb (2x faster)
clock_refe=clock();
for(;modulo.counter<1000000000;modulo.counter++)
{
// i need accumulated randoms for later use for some std. dev. thing.
random_modulus.randoom=rand();
array_1[modulo.lsb]+=random_modulus.lsb;
}

//getting average clock cycles
for(int i=0;i<65536;i++)
{
array_mean+=array_1[i];

}
array_mean/=65536.0f;

//getting square of deltas
float array_2[65536];

for(int i=0;i<65536;i++)
{
array_2[i]=(array_1[i]-array_mean)*(array_1[i]-array_mean); 
}


//horizontal histogram for resoluton of 20 elements
for(int i=0;i<65536;i+=(65536)/20)
{


for(int j=0;j<(array_2[i]*0.01);j++)
{

    printf("*");
}
printf("\n");
}

//calculations continue .....
return 0;

}

某些数组中预先计算的值可能?但如果我只使用%calc部分一次,这是相同的。你能给出一些关于按位操作手册的书籍参考吗?

1 个答案:

答案 0 :(得分:1)

在这种情况下,按位运算是最便携的方法。这是一些示例函数;它们是为了便于阅读而编写的,但可以更快地制作:

int lsb(int input) {
    int mask = 0x00FF; // 0x00FF is 0000000011111111 in binary
    return input & mask;
}

int msb(int input) {
    int mask = 0xFF00; // 0xFF00 is 1111111100000000 in binary
    return (input & mask) >> 8;
}

通常,使用&屏蔽所需的位,然后使用>>将它们对齐到右侧。 K&amp; R第二版(由Brian Kernighan和Dennis Ritchie编写的C语言)提供了关于每个C主题的信息,包括位掩码。

如果你希望a % b b不是2的幂,那么本地%运算符是最快的方式(在现代编译器中,它与按位运算一样快,即使b是2的力量。但是,按位运算在其他环境中很有用。