What is an unsigned char?

2019-01-01 04:32发布

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

标签: c++ c char
16条回答
大哥的爱人
2楼-- · 2019-01-01 04:44

If you like using various types of specific length and signedness, you're probably better off with uint8_t, int8_t, uint16_t, etc simply because they do exactly what they say.

查看更多
无与为乐者.
3楼-- · 2019-01-01 04:45

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.

查看更多
情到深处是孤独
4楼-- · 2019-01-01 04:46

signed char has range -128 to 127; unsigned char has range 0 to 255.

char will be equivalent to either signed char or unsigned char, depending on the compiler, but is a distinct type.

If you're using C-style strings, just use char. If you need to use chars for arithmetic (pretty rare), specify signed or unsigned explicitly for portability.

查看更多
像晚风撩人
5楼-- · 2019-01-01 04:47

An unsigned char uses the bit that is reserved for the sign of a regular char as another number. This changes the range to [0 - 255] as opposed to [-128 - 127].

Generally unsigned chars are used when you don't want a sign. This will make a difference when doing things like shifting bits (shift extends the sign) and other things when dealing with a char as a byte rather than using it as a number.

查看更多
路过你的时光
6楼-- · 2019-01-01 04:51

unsigned char takes only positive values: 0 to 255 signed char takes positive and negative values: -128 to +127

查看更多
不再属于我。
7楼-- · 2019-01-01 04:56

If you want to use a character as a small integer, the safest way to do it is with the int8_tand uint8_t types.

查看更多
登录 后发表回答