码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-13 20:50:32      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   sp   on   2014   log   

十六进制数相等的判断

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

#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十六进制数

标签:blog   http   io   ar   os   sp   on   2014   log   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!