unsigned char

When do we use unsigned char ? (and not simply "char").
(I know that unsigned char can be 0,..255 and char can be -128 , .. +127)


The only time I've used it is in the graphics component for a game I made, each colour channel was represented by one 'byte' which was an unsigned char. Colours of course can't have negative values for red, green and blue.
Everywhere where you deal directly with bytes.
Only in rare cases it is desirable to treat bytes as signed numbers.
Can you explain ? Do you mean when you use integer with byte size ?
or do you mean when you use char ?
Thanks
in C actually the data type dosent mean anything other than size, at the most of the times.. so, if you want to store some 256 numbers, you can use unsigned char and easily manipulate them.. i suggest you learn about Hashing... too... it will give you an idea, what really you can do with bits and bytes...
http://en.wikipedia.org/wiki/Hash_function
http://en.wikipedia.org/wiki/Hash_table
i hope this helps...
cheers..
Just thought I'd post a tip.

Regardless of signedness, mixing signed and unsigned types is bad stuff. unsigned char is sometimes more useful because bytes are thought of as 0-127 in ASCII (and 128-255 in environments that make use of IBM extended characters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* char is always signed unless otherwise specified
   (some compilers offer options to make it default to unsigned).

   As a signed char it is -20,
   and as an unsigned char, it is 236,
   both of which are represented as 0xEC.  */
unsigned char uc = 0xEC;
char sc = uc;

/* -20 as a 32-bit signed integer is 0xFFFFFFEC;
    236 as a 32-bit signed integer is 0x000000EC.  */
int i = sc;
int j = uc;
cout << i << endl;
cout << j << endl;


While this behaviour is expected in the example code above, it isn't always expected in the case of comparisons. For example, suppose you did i == j. As signed and unsigned char values they were represented the same. However, the signed char value was sign-extended while the unsigned char value was padded with zeroes. Because of that, i and j are NOT equal despite being the same signedness now.

This annoyance can cause issues in your code, and it can show itself at the worst of times. Be careful!
Last edited on
Topic archived. No new replies allowed.