Go Down

Topic: The char variable (Read 1 time) previous topic - next topic

sparkylabs

I have just been reading about the character variable. Now reading between the lines this was a roundabout way of saying that it is a one byte variable that contains the ASCII codes of what ever character is put into it. So how can this variable have negative and positive numbers? This does not make sense the ASCII code goes from 0 to 255 why do you even need negative numbers in this bearable type?

marco_c

The char is equivalent to an unsigned byte or uint8_t. They take up the same amount of space (8 bits). Whether something is negative or positive depends on the interpretation of the bits, so 0xff can be 255 or -1. Look up 'two's complement' to find out how this works.
Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

Arrch


I have just been reading about the character variable. Now reading between the lines this was a roundabout way of saying that it is a one byte variable that contains the ASCII codes of what ever character is put into it. So how can this variable have negative and positive numbers? This does not make sense the ASCII code goes from 0 to 255 why do you even need negative numbers in this bearable type?

Just depends on the context. Unsigned and signed variables are just interpreted differently, but they are stored the same in memory.

Nick Gammon


The char is equivalent to an unsigned byte or uint8_t.


It's actually a signed byte. It is "byte" that is unsigned.

Quote
This does not make sense the ASCII code goes from 0 to 255 why do you even need negative numbers in this bearable type?


It's a bit of a historical throwback, I think. It doesn't make sense to have "negative" letters, so really the byte (unsigned char) would have been a better choice. But as the others said, when stuffing ASCII codes into a byte (or char) you don't care about the sign because you won't be doing arithmetic on it.

marco_c

#4
May 23, 2012, 03:05 am Last Edit: May 23, 2012, 03:07 am by marco_c Reason: 1
Oops!

Actually a related question from me is how Arduino would support double byte or Unicode characters now that the interface supports multiple languages, or is it just not an issue in this environment?
Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

Go Up