On what occasions should I use an unsigned char or a char in C?

Asked

Viewed 2,701 times

1

Recently I’ve been reading a little bit about the difference between a char and a unsigned char. I was able to understand the basic difference between the two, however, I didn’t get the idea behind the use of a unsigned char, or better, I hardly know when is the right time to use a char or a unsigned char.

Therefore, I come here with the following question: On what occasions should I use a unsigned char or a char in C?

  • 1

    Related or duplicate: https://answall.com/q/77418/101

  • @Maniero It is a pity that I can not exclude the question ... only my account ( ° ʖ °)

  • https://www.vivaolinux.com.br/topico/C-C++/Em-quais-ocasioes-devo-utilizar-um-unsigned-char-ou-um-char-em-C

1 answer

1

Basically not only in char as in int, float among others, we have the Signed and unsigned types (there are others besides them), the difference is that the most significant bit that makes the change from positive values to negative is ignored and used as space, Thus it is released but space, already in contrast the negative numbers are not possible. See the following table, all unsigneds start with 0

Obs: It is worth mentioning that Signed is used by default therefore you declare

signed char = 2;

and declare

char = 2;

would have done the same

inserir a descrição da imagem aqui

So answering the question you declare a char the maximum that can be inserted in it would be 127

char valor = 127;

already putting it to insigned it goes up to the 255 so it would be possible to do

unsigned char valor = 255;

however it would not be possible to add negative in unsigned.

Why does that happen? let’s take the char as example, the char contains 8 bits, so the possible values (1 or 0) we have 2 options among 8 bits, raising it would be 2 8 = 256 and so we have 0 to 255 space, but among these 8 bits, 1 is used to change, determine whether it is negative or positive and it is possible to use 7, thus 2 7 = 128 if counting from 0 would be 0 - 127.

So char still uses the bit for positive and negative causing it to be 127 of maximum size, so if you use unsigned and ignore this it would be possible to use the 8 bits ignoring the control of positive and negative, getting 2 8 = 256, so counting from 0 we would be with 255 of maximum size in char.

  • Dude ... erase the answer because I want to erase the question!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.