关于char 和 unsigned char

来源:百度文库 编辑:神马文学网 时间:2024/04/29 02:43:49

char 是有符号的

unsigned char 是无符号的,里面全是正数

 

两者都作为字符用的话是没有区别的,但当整数用时有区别:

char 整数范围为-128127( 0x80__0x 7F)  

unsigned char 整数范围为0255( 0__0xFF )

 

多数情况下,char ,signed charunsigned char 类型的数据具有相同的特性然而当你把一个单字节的数赋给一个大整型数域时,便会看到它们在符号扩展上的差异。另一个区别表现在当把一个介于128255之间的数赋给signed char 变量时编译器必须先进行数值转化,同样还会出现警告。

 

看下面的函数。

功能:统计字符串里面的汉字的个数

 gb2312编码内码大于0xa0,0xa0是十进制的160远大于127,在ASCII中,0xa0表示汉字的开始。

 

char sText[]= "12345你好";

 

len = strlen(sText);

int sum=0;

for (int i=0; i< len; i++)

{

    // The ASCII of character >= 65

if (sText[i] > 64)

{

sum++;

}

}

 

这样你根本统计不到任何汉字,

因为char是有符号的,最大就是127,超过就变成负数了。比如7f127,那么80就是-1了。

这时候你一定要写成

unsigned char sText[]= "12345你好";

 

 

参考程序:

 

#include

#include

 

using namespace std;

 

int main()

{

    unsigned char sText[]= "12345Hello";

    int len = 0;

    char temp;

 

    // unsigned int strlen(const char *s);

    // We need to convert sText from unsigned char* to const char*

    len = strlen((const char*)sText);

    cout<<"The strlen is"<

    int sum=0;

    for(int i=0; i< len; i++)

    {

        // The ASCII of character >= 65

        if (sText[i] > 64)

        {

            sum++;

        }

        cout<<"Character count:"<

    }

 

    // just to have a pause

    cout<<"Enter any thing to exit!"<

    cin>>temp;

 

    return 0;

}