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


当前回答

Char和unsigned Char不能保证在所有平台上都是8位类型——它们保证是8位或更大的类型。一些平台有9位、32位或64位字节。然而,今天最常见的平台(Windows、Mac、Linux x86等)都有8位字节。

其他回答

一些人在谷歌上找到了这个,人们对此进行了讨论。

无符号字符基本上是一个单字节。所以,如果你需要一个字节的数据,你可以使用它(例如,也许你想用它来设置标志的开启和关闭,以传递给一个函数,就像在Windows API中经常做的那样)。

Signed char的范围是-128到127;Unsigned char的范围是0到255。

根据编译器的不同,Char将等价于有符号Char或无符号Char,但它是一种不同的类型。

如果你使用c风格的字符串,只使用char。如果需要使用字符进行算术运算(非常少见),请显式指定signed或unsigned以实现可移植性。

无符号字符使用为常规字符的符号保留的位作为另一个数字。这将范围更改为[0 - 255],而不是[-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.

Unsigned char只取正值:0到255 while Signed char有正负值:-128到+127。