首页 > 其他 > 详细

网络编程中的常见陷阱之 0x十六进制数

时间:2014-11-13 20:48:36      阅读:259      评论:0      收藏:0      [点我收藏+]

十六进制数相等的判断

请问如下程序的输出是神马?

#include <iostream>
#include <string>
using namespace std;

int  main (int, char *[])
{
    char s[1]={0};

    s[0] = 0xfe;
    if (s[0] == 0xfe)
    {
        cout<<"=="<<endl;
    }
    else
    {
        cout<<"!="<<endl;
    }

    return 0;
}

bubuko.com,布布扣

为何不相等呢?

看截图:

bubuko.com,布布扣

具体原因:http://zhidao.baidu.com/question/198400742.html?qbl=relate_question_1&word=C%2B%2B%20%CA%FD%D6%B5%C4%AC%C8%CF%C0%E0%D0%CD

正确的做法:

#include <iostream>
#include <string>
using namespace std;

int  main (int, char *[])
{
    char s[1]={0};
    s[0] = (char)0xfe;// s[0] = fe , s[0] < 0
    if (s[0] == (char)0xfe) //禁止类型转换到int
    {
        cout<<"=="<<endl;
    }
    else
    {
        cout<<"!="<<endl;
    }
    return 0;
}

所以,char变量赋值常数的时候要强制转换,判断相等的时候避免转换到int




网络编程中的常见陷阱之 0x十六进制数

原文:http://blog.csdn.net/calmreason/article/details/41085115

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!