long 与int 比较问题

long 与int 比较,在32位机器,sizeof都是 占用4个字节;

在window 64位也是占用4个字节

但是在Linux 64位,long占用 8个字节, int占用4个字节,这样比较就会有问题。 当int 强转 位long时,发生 int高位1(符号位1)转为long的高位1(补全) 出现大的值。

譬如:     int 0x80650008 (-2140864504) 高位1,是一个负值,

    强转位long 0xFFFFFFFF80650008 (-2140864504) , 这样就出现问题了。

 

下面这段代码TTSAPIERROR 实际上是32位,那么只需要比较32位即可,可以将long 强转为int

#include "stdio.h"

#ifndef SCODE
#define SCODE long
#endif

#ifndef MAKE_SCODE
#define MAKE_SCODE(sev,fac,code) \
        ((SCODE) (((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))) )
#endif

#define FACILITY_TTSAPI   (0x65)
#define SEVERITY_ERROR      1
#define TTSAPIERROR(x)    MAKE_SCODE(SEVERITY_ERROR,   FACILITY_TTSAPI, (x & 0x0000FFFF))

int main()
{

    //error code  
    int ret = TTSAPIERROR(0x08);
    long ret2 = (long)ret;

    if(ret2 == TTSAPIERROR(0x08))
    {   
        printf("find error, 0x08 \n");
    }   
    
    //show
    printf("%d %ld ,%ld \n", ret, ret2, TTSAPIERROR(0x08));

    printf("--ul:%d  l:%d \n",sizeof(unsigned long), sizeof(long));
    return 0;
}

运行:

[root@localhost:/data/lkchu]# gcc -m64 test.c
[root@localhost:/data/lkchu]# ./a.out 
-2140864504 -2140864504 ,2154102792 
--ul:8  l:8 
[root@localhost:/data/lkchu]# gcc -m32 test.c
[root@localhost:/data/lkchu]# ./a.out 
find error, 0x08 
-2140864504 -2140864504 ,-2140864504 
--ul:4  l:4 

 

将代码修改为

int main()
{

    //error code  
    int ret = TTSAPIERROR(0x08);
    long ret2 = (long)ret;

    if(ret == (int)TTSAPIERROR(0x08))
    {   
        printf("find error, 0x08 \n");
    }   
    
    //show
    printf("%d %ld ,%ld \n", ret, ret2, TTSAPIERROR(0x08));

    printf("--ul:%d  l:%d \n",sizeof(unsigned long), sizeof(long));
    return 0;
}

 

posted on 2017-06-02 09:11  偏爱省略号  阅读(8081)  评论(0编辑  收藏  举报

导航