在C/ c++中,unsigned char是用来干什么的?它和常规char有什么不同?


当前回答

有符号char和无符号char都表示1字节,但它们的范围不同。

   Type        |      range
-------------------------------
signed char    |  -128 to +127
unsigned char  |     0 to 255

在signed char中,如果我们考虑char letter = 'A', 'A'在ASCII/Unicode中代表65的二进制,如果65可以存储,-65也可以存储。在ASCII/Unicode中没有负二进制值,所以不需要担心负数。

例子

#include <stdio.h>

int main()
{
    signed char char1 = 255;
    signed char char2 = -128;
    unsigned char char3 = 255;
    unsigned char char4 = -128;

    printf("Signed char(255) : %d\n",char1);
    printf("Unsigned char(255) : %d\n",char3);

    printf("\nSigned char(-128) : %d\n",char2);
    printf("Unsigned char(-128) : %d\n",char4);

    return 0;
}

输出-:

Signed char(255) : -1
Unsigned char(255) : 255

Signed char(-128) : -128
Unsigned char(-128) : 128

其他回答

unsigned char是一个无符号字节值(0到255)。你可能认为char是一个“字符”,但它实际上是一个数值。常规字符是带符号的,因此有128个值,这些值映射到使用ASCII编码的字符。但无论哪种情况,您在内存中存储的都是字节值。

如果你喜欢使用各种类型的特定长度和符号,你可能更好的uint8_t, int8_t, uint16_t等,因为他们完全做他们说。

摘自《c语言编程》一书:

有符号或无符号限定词可以应用于char或任何整数。无符号数 都是正的或零的,并且服从对2^n取模的算术法则,其中n是数字 类型中的位。例如,如果字符是8位,unsigned char变量就有值 在0到255之间,而有符号字符的值在-128到127之间 补机)。纯字符是有符号字符还是无符号字符取决于机器, 但是可打印的字符总是正的。

Unsigned char只取正值....比如0到255

Signed char同时取正负值....比如-128到+127

例如unsigned char的用法:

Unsigned char经常用于计算机图形,它经常(虽然不总是)为每个颜色组件分配一个字节。通常可以看到RGB(或RGBA)颜色表示为24(或32)位,每个位都是unsigned char。由于unsigned char值落在[0,255]范围内,这些值通常被解释为:

0表示完全缺乏给定的颜色组件。 255表示某一特定色素的100%。

所以你最终会得到RGB红色为(255,0,0)->(100%红,0%绿,0%蓝)。

Why not use a signed char? Arithmetic and bit shifting becomes problematic. As explained already, a signed char's range is essentially shifted by -128. A very simple and naive (mostly unused) method for converting RGB to grayscale is to average all three colour components, but this runs into problems when the values of the colour components are negative. Red (255, 0, 0) averages to (85, 85, 85) when using unsigned char arithmetic. However, if the values were signed chars (127,-128,-128), we would end up with (-99, -99, -99), which would be (29, 29, 29) in our unsigned char space, which is incorrect.