unsigned char 与char的区别

Character values of type unsigned char have a range from 0 to 0xFF hexadecimal. A signed char has range 0x80 to 0x7F. These ranges translate to 0 to 255 decimal, and –128 to +127 decimal, respectively. The /J compiler option changes the default from signed to unsigned.

signed char的范围是-127到+127
对于双字节编码,比如一个汉字的GB编码为2个字节,高字节的最高位为1,即高字节>127。通常需要转换为unsigned char进行判断,请大家注意这一点。如:

while (*p)
{
if ((unsigned char)*p > 127) //汉字
{
p += 2;
}
else //标准的ASCII字符
{
p += 1;
}
}

 

 

char 是有符号的

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

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

char 整数范围为-128到127( 0x80__0x7F),  

而unsigned char 整数范围为0到255( 0__0xFF )

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

看下面的函数。

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

char sText[]= "12345Hello";

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,超过就变成负数了。比如7f 是127,那么80就是-1了。

这时候你一定要写成

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

参考程序:

#include <iostream>

#include <string.h>

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"<<len<<endl;

    int sum=0;

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

    {

        // The ASCII of character >= 65

        if (sText[i] > 64)

        {

            sum++;

        }

        cout<<"Character count:"<<sum<<endl;

    }

    // just to have a pause

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

    cin>>temp;

    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值