zoukankan      html  css  js  c++  java
  • 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.

    char 是有符号

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

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

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

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

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

    看下面的函数。

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

     1 char sText[]= "12345Hello";
     2 len = strlen(sText);
     3 int sum=0;
     4 for (int i=0; i< len; i++)
     5 {
     6 // The ASCII of character >= 65
     7 if (sText[i] > 64)
     8 {
     9 sum++;
    10 }
    11 }

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

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

    参考程序:

    #include <iostream>
    #include <string.h>
    using namespace std;
    int main()
    {
    unsigned char sText[]= "12345你好";
    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;
    }

    运行结果:

    把unsigned char sText[]= "12345你好";改成char sText[]= "12345你好",运行结果:

  • 相关阅读:
    jquery 初篇
    python作用域和js作用域的比较
    javascript作用域
    第三篇、dom操作续
    dom事件
    第二篇 dom内容操作之value
    第三篇、变量
    第二篇、常量
    Node.js
    测试用例
  • 原文地址:https://www.cnblogs.com/wbb2109/p/2695875.html
Copyright © 2011-2022 走看看