long 與int 比較問題

long 與int 比較,在32位機器,sizeof都是 佔用4個字節;spa

在window 64位也是佔用4個字節code

可是在Linux 64位,long佔用 8個字節, int佔用4個字節,這樣比較就會有問題。 當int 強轉 位long時,發生 int高位1(符號位1)轉爲long的高位1(補全) 出現大的值。blog

譬如:     int 0x80650008 (-2140864504) 高位1,是一個負值,io

    強轉位long 0xFFFFFFFF80650008 (-2140864504) , 這樣就出現問題了。class

 

下面這段代碼TTSAPIERROR 其實是32位,那麼只須要比較32位便可,能夠將long 強轉爲inttest

#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;
}

運行:gcc

[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 

 

將代碼修改成gc

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;
}
相關文章
相關標籤/搜索