• 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 
    ");
        }   
        
        //show
        printf("%d %ld ,%ld 
    ", ret, ret2, TTSAPIERROR(0x08));
    
        printf("--ul:%d  l:%d 
    ",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 
    ");
        }   
        
        //show
        printf("%d %ld ,%ld 
    ", ret, ret2, TTSAPIERROR(0x08));
    
        printf("--ul:%d  l:%d 
    ",sizeof(unsigned long), sizeof(long));
        return 0;
    }
  • 相关阅读:
    MD5 带salt 加密
    生成包含数字和大小写字母的随机码
    多读好代码助于提高
    Winform程序窗体间的跳转
    Sql Server 存储过程
    GDI+的学习
    管理人生的8个危机
    马云语录
    无边框窗体的拖动和拉伸
    安装oracle时遇到 环境变量path的值超过1023字符,无法设置该值
  • 原文地址:https://www.cnblogs.com/iclk/p/6931742.html
Copyright © 2020-2023  润新知