What is an unsigned char?

后端 未结 17 1158
借酒劲吻你
借酒劲吻你 2020-11-22 11:05

In C/C++, what an unsigned char is used for? How is it different from a regular char?

17条回答
  •  名媛妹妹
    2020-11-22 11:19

    As for example usages of unsigned char:

    unsigned char is often used in computer graphics, which very often (though not always) assigns a single byte to each colour component. It is common to see an RGB (or RGBA) colour represented as 24 (or 32) bits, each an unsigned char. Since unsigned char values fall in the range [0,255], the values are typically interpreted as:

    • 0 meaning a total lack of a given colour component.
    • 255 meaning 100% of a given colour pigment.

    So you would end up with RGB red as (255,0,0) -> (100% red, 0% green, 0% blue).

    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.

提交回复
热议问题