LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   signed and unsigned (https://www.linuxquestions.org/questions/programming-9/signed-and-unsigned-447416/)

ArthurHuang 05-22-2006 01:37 PM

signed and unsigned
 
what's the difference with these three definitions?

char
signed char
unsigned char?

Generally, when and how to use them?

(Networking, scientific computing)????

Mega Man X 05-22-2006 01:43 PM

Well, a signed char can have either positive or negative values, while an unsigned char can only have positive values. Ex:

Code:

signed char myChar = 10;
signed char newChar = -3;
unsigned char yourChar = 100;

in the case you have only a char:

Code:

char anotherChar = 20;
it's up to the compiler to define if it will be either signed or unsigned by default.

tuxdev 05-22-2006 01:47 PM

This feels like a HW question. Read K&R 2.2, 2.9 if you've got it around.

ta0kira 05-22-2006 02:36 PM

'char' is just a number, like 'short' and 'long'. Since it has only 256 values, we choose to generally represent letters using 'char' and binary using 'unsigned char', though the computer sees them both as 1 byte numbers. The usual default is 'signed', but you always have the option of making it explicit. The C++ standard says that any pointer can be cast to 'unsigned char*' for binary representation without "undefined behavior", which is why it's mostly used for working with single bytes of raw data. Really, the only thing different between the two is how arithmetic other than + and - affect them, and how std::cout (in C++) would choose to display them (and, of course, the pointer types don't implicitly convert.)
ta0kira

Wim Sturkenboom 05-23-2006 03:46 AM

You use 'unsigned char' when you want the compiler to treat it as unsigned.
An example
Code:

char a=127,b=1,c;

    c=a+b;
    printf("a+b=%d+%d=%d\n",a,b,c);

    a=0x01; //  1 signed,  1 unsigned
    b=0xff; //  -1 signed, 255 unsigned

    if(a>b) printf("a greater than b\n");
    else  printf("a smaller than (or equal to) b\n");

The result:[code]a+b=127+1=-128
a greater than b[/code[
Change the char in the code to unsigned char and this will be the result:
Code:

a+b=127+1=128
a smaller than b

If char is used as a character, it does not matter to much as characters are usually 7-bit (ascii table).
If you're however programming in a dos/windows environment, you will have the extensions (like à,ç etc which are the values 128 to 255).
When comparing the characters (a<b or a>=b), the sign is important (see above example).


All times are GMT -5. The time now is 05:26 PM.