读书人

字符小疑点

发布时间: 2012-03-21 13:33:15 作者: rapoo

字符小问题

C/C++ code
#include <iostream>#include <string.h>using namespace std;bool IsNull(void *buf,  int nLength){    int nIndex = 0;    char *sBuf = (char *)buf;    for (nIndex = 0; nIndex < nLength; nIndex ++)    {        if ( *(char *)(sBuf + nIndex) != 0xff)            //这里为什么不相等啊???        {            return false;        }    }    return true;}int main(){    int nData = 0xffffffff;    printf("%d \n", IsNull((void *)&nData, 4));    return 0;}


为什么结果不是true啊?

[解决办法]
char 的范围是-128~127, 所以*(char *)(sBuf + nIndex) = -1, 不是0xff
你可以改成if ( *(unsigned char *)(sBuf + nIndex) != 0xff)

读书人网 >C++

热点推荐