这个值是如何计算的?

时间:2014-03-01 08:56:42

标签: c

#define     no          14022014L

unsigned long Pack(unsigned long num){
    unsigned long tmp;
    unsigned char *s=NULL;
    int k = 0;
    int sz_long = sizeof(unsigned long); 
    if (num ) {
        tmp=0L;
        s = (unsigned char *) &tmp;
        while(sz_long){
            k=(--sz_long)<<3;
            printf("k = %d\n", k);
            k=(int)(num >> k );
            printf("k=num >> k=%d\n", k);
            k=k & 0xFF;
            printf("k=k & 0xFF=%d\n", k);
            *s++ = (unsigned char) k;
            printf("tmp = %lu\n", tmp);
        }
        return tmp;
    }
    return num;
}


int main(void){
    unsigned long t;
    t=Pack(no);
    if ( t) {
        printf("t = %lu\n", t);
    }
    return 0;
}

输出

Pack
k = 24
k=num >> k=0
k=k & 0xFF=0
tmp = 0
k = 16
k=num >> k=213
k=k & 0xFF=213
tmp = 54528              // how ?
k = 8
k=num >> k=54773
k=k & 0xFF=245
tmp = 16110848            // how ?
k = 0
k=num >> k=14022014
k=k & 0xFF=126
tmp = 2130040064          // how ?

Main()
t = 2130040064

问:如何计算tmp的值?

2 个答案:

答案 0 :(得分:1)

该算法一次构建一个字节的长值。如果您将所有格式更改为十六进制,您应该能够更清楚地看到正在构建的数字。

答案 1 :(得分:1)

如前所述,将tmp值视为十六进制非常有用:

k = 24
k=num >> k=0
k=k & 0xFF=0
tmp = 0
k = 16
k=num >> k=213
k=k & 0xFF=213 // d5
tmp = d500
k = 8
k=num >> k=54773
k=k & 0xFF=245  // f5
tmp = f5d500
k = 0
k=num >> k=14022014
k=k & 0xFF=126  // obviously 7e
tmp = 7ef5d500
t = 2130040064

您的代码将tmp填充为翻转no值:

printf("t = %x, no = %x\n", t, no);
t = 7ef5d500,
no = d5f57e