在C/ c++中,unsigned char是用来干什么的?它和常规char有什么不同?
当前回答
例如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.
其他回答
摘自《c语言编程》一书:
有符号或无符号限定词可以应用于char或任何整数。无符号数 都是正的或零的,并且服从对2^n取模的算术法则,其中n是数字 类型中的位。例如,如果字符是8位,unsigned char变量就有值 在0到255之间,而有符号字符的值在-128到127之间 补机)。纯字符是有符号字符还是无符号字符取决于机器, 但是可打印的字符总是正的。
这取决于实现,因为C标准没有定义char的符号性。根据平台的不同,char可能是有符号的,也可能是无符号的,因此如果您的实现依赖于它,则需要显式地请求有符号char或无符号char。如果您打算表示字符串中的字符,则使用char,因为这将与您的平台在字符串中放入的内容相匹配。
有符号char和无符号char之间的区别正如您所期望的那样。在大多数平台上,signed char将是一个8位的2补数,范围从-128到127,unsigned char将是一个8位的无符号整数(0到255)。注意标准并不要求char类型有8位,只要求sizeof(char)返回1。你可以在limited .h中使用CHAR_BIT获取一个char的比特数。然而,如今很少有平台会使用8以外的东西。
这里对这个问题有一个很好的总结。
正如其他人在我发布这篇文章后提到的,如果你真的想表示小整数,你最好使用int8_t和uint8_t。
unsigned char是一个无符号字节值(0到255)。你可能认为char是一个“字符”,但它实际上是一个数值。常规字符是带符号的,因此有128个值,这些值映射到使用ASCII编码的字符。但无论哪种情况,您在内存中存储的都是字节值。
如果你喜欢使用各种类型的特定长度和符号,你可能更好的uint8_t, int8_t, uint16_t等,因为他们完全做他们说。
例如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.
推荐文章
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 公共朋友交换成员函数
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 如何在Go中使用c++
- 自定义c++分配器的引人注目的例子?
- RAII和c++中的智能指针
- 如何构建和使用谷歌TensorFlow c++ api
- C“int”的大小是2字节还是4字节?
- 多维数组如何在内存中格式化?
- printf()和puts()在C语言中的区别是什么?
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 有效,但毫无价值的语法在开关情况下?