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


当前回答

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

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

其他回答

Unsigned char只取正值:0到255 while 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.

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

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

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

无符号字符使用为常规字符的符号保留的位作为另一个数字。这将范围更改为[0 - 255],而不是[-128 - 127]。

当你不想要符号时,通常使用无符号字符。这在处理像移位位(移位扩展符号)和其他将字符作为字节处理而不是将其作为数字处理时会产生不同。