In C/C++, what an unsigned char
is used for? How is it different from a regular char
?
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:
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 char
s (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.