关于unsigned char和signed char的问题

来源:互联网 发布:胡歌演技 知乎 编辑:程序博客网 时间:2024/04/30 15:08
unsigned char与char的区别
2007-10-18 11:24

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.
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;
}

 

在定义一个8位变量和字符型变量时,很多人爱使用unsiged char而不喜欢使用char,其主要原因是unsigned char的取值范围是0~255,而char的取值范围是-128~+127,一般人不处理负的数值,所以认为unsigned char往往能够兼容char。

 
       ANSI标准的ASCII字符的允许范围是0~127,这已经涵盖了我们常用的字符(有些计算机系统还扩充使用128~255的字符,但那些字符一般场合使用很少)。如果要使用指向字符型的指针时,使用char来定义则要好得多,这主要是能够在使用keil调试过程中带来额外好处:可以通过keil的“watch and call stack window”变量观察窗直接观察到该指针指向的字符串内容,而将指针定义成unsigned char 则只能以十进制或者十六进制显示。

现在我正在学习C++,用的书是《C++   Primer》(3rd   Edition)。在这本书的Chapter   3中介绍char类型时,有这么一句话:  
  An   8-bit   signed   char   may   represent   the   values   -128   through   127;  
  an   unsigned   char,   0   through   255.  
  所以我写了段代码对其进行测试:  
  #include   <iostream>  
  using   namespace   std;  
   
  int   main()  
  {  
          signed   char   c   =   127;  
          cout   <<   c+1   <<   endl;  
          return   0;  
  }  
  编译通过,但是输出128。  
  这是为什么?  
   
  PS:我用的编译器是Dev-C++带的g++。 

回复:::

你输出的是c+1的值,编译器先生成一个临时变量temp,计算temp=c+1,输出的当然是128啦;

c+1   的类型是什么,扩展了当然不会在0-127   范围,  
  如果你用  
  signed   char   d=c+1;   这就不行了。你可以看到 i变成了 -128   (溢出了)  
  #include   <iostream>  
  using   namespace   std;  
   
  int   main()  
  {  
          signed   char   c   =   127;  
          signed   char   d;  
          d=c+1;  
          int   i=d;  
          cout   <<   c+1<<"/n"<<i<<   endl;  
          return   0;  
  }   
   
编译器会把她提升到int,如果你直接让c=1000。那么编译器会给出警告的。但是不会出错。

原创粉丝点击