0
hey anyone can tell plz what is unsigned char and signed char and why it is? whats the difference from normal char?
what if we enter -1 in unsigned char?plz explain in detail. any effort will be highly appreciated.thanks in advance
6 Respuestas
+ 2
Take few minutes and read this article
https://twiserandom.com/c/what-is-char-signed-char-unsigned-char-and-character-literals-in-c/
+ 2
unsigned char can only take in positive numbers while signed char can take positive and negative numbers.
the downside is that it can only hold less amount of maximum numbers.
+ 2
read how two's complement works
gaurav kumar
+ 1
In regards to "the downside is that it can only hold less amount of maximum numbers." The scope of numbers is still the same. Their are 256 available numbers.
With a signed char:
Min value: -128
Max value: 127
Value range: -128 to 127 (256 possible numbers inclusive of 0)
Unsigned char:
Min value: 0
Max value: 255
Value range: 0 to 255 (256 possible numbers inclusive of 0)
If you use signed char you will not be able to reach the ANSI characters from 128 to 255.
Why use signed or unsigned char, char is a variable type that is expressed with 8 bits or 1 byte therefore takes up less memory than other data types.
This next part may be compiler specific so forgive me if I am a bit off. To your question "what if we enter -1 in unsigned char?"
If we run this:
#include <stdio.h>
int main(void){
unsigned char usc = -1;
char sc = -1;
printf("unsigned char -1 equals %i or %x\nsigned char -1 equals %i or %x\n", usc, usc, sc, sc);
}
The output would be:
unsigned char -1 equals 255 or ff
signed char -1 equals -1 or ff
This is because the -1 on the unsigned has value of 0 to 255 but still the program looks at the 8 bits which for -1 is represented by 11111111 and also equivalent to 255 in an unsigned char.
+ 1
last part again plz William Owens how program looks -1 as 11111111
thanks for answering man
+ 1
Two's complement does not come into play because the destination type is an unsigned integer type, whereas two's complement is one of the integer representation systems used for signed integer types. Rather, this conversion rule is relevant:
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2**n where n is the number of bits used to represent the unsigned type). [ Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]