tl;dr : Since unsigned char is represented as a byte value, the output to the serial is the byte representation, not the char
I re-wrote the code you had for reference:
#define CHARS 255
#define BAUD 115200
unsigned char unsChar[CHARS];
char sinChar[CHARS];
void setup() {
Serial.begin(BAUD);
Serial.println("~~Setup~~");
for(int i = 0; i < CHARS; i++) {
unsChar[i] = (unsigned char)i;
sinChar[i] = (char)i;
}
}
void loop() {
Serial.println("~~Loop~~");
for(int i = 0; i < CHARS; i++) {
Serial.print("INDEX : ");
Serial.println(i);
Serial.print("unsigned char: ");
Serial.println(unsChar[i]);
Serial.print(" char: ");
Serial.println(sinChar[i]);
Serial.println("---------------------");
}
delay(10000);
}
When you run this you'll see the unsigned char
is simply printed to the serial like any other byte
value but the char
value is printed as a character according to the ASCII chart.
If you compare the documentation for unsigned char
An unsigned data type that occupies 1 byte of memory. Same as the byte datatype.
The unsigned char datatype encodes numbers from 0 to 255.
For consistency of Arduino programming style, the byte data type is to be preferred.
versus a normal (signed) char
:
A data type used to store a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").
Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See Serial.println
reference for more on how characters are translated to numbers.
The size of the char datatype is at least 8 bits. It’s recommended to only use char for storing characters. For an unsigned, one-byte (8 bit) data type, use the byte data type.
So size wise an array of chars and unsigned chars are going to be the same. It's more about the representation of the underlying number (byte) and what works best for your use case.
char
andunsigned char
? Unlike e.g. what standardiostream
seems to do: bothunsigned char uc = 0x41; cout << uc << endl;
andchar c = 0x41; cout << c << endl;
outputA
.