# Variables 101, char

#### misterT

##### Well-Known Member
char

The most important variable type in 8-bit microcontroller is char. It holds 8-bits of data, which makes it very efficient for an 8-bit microcontroller to process.

A char can hold many kinds of information. An ASCII character, a decimal number, hexadecimal or bit pattern. Here are examples how you can assign these different types of data into char-variable.

C:
/* Declare four char variables */
char a, b, c, d;

a = 85;         // Decimal value
c = 0b01010101; // Bit pattern
d = 'U';        // Ascii character. Notice the use of apostrophes '
Actually, all the assigned values in above example are exactly the same. They all have exactly the same presenetation (bit pattern) inside the microcontroller. Only thing different is how you are intending to use the variable. You should always choose the most meaningful way to present data.

You can check the values by googling "0b01010101 to hex" or "0x55 to decimal". I also recommend that you google up an "ASCII table" and take a look at it.

A char variable can be unsigned or signed. C standard does not unfortunately say which one should be the default. It is better to explicitly declare variable either unsigned or signed.

C:
char a;          // Can be signed or unsigned depending what compiler you use
unsigned char b; // Unsigned. Can hold values from 0 to 255
signed char c;   // Signed. Can hold values from -128 to 127

c = 0b10000000; // c is a negative number -128. The leftmost bit is a sign-bit
/* Negative values are stored in so-called 2's complement representation,
which is another topic itself. */
It is good practice to use unsigned char when working with ASCII characters, bit patterns etc. Use signed char only when you need negative numbers.

There is a trap with signed char which can break your code. And the problem can be extremely difficult to find. When bit shifting a negative number to the right, it is filled with ones instead of zeros.

C:
unsigned char a;
signed char b;

/* Shift unsigned char three times right */
a = 0b10000000; // a is decimal number 128
a = a >> 3;     // After the shif a holds the value 0b00010000.

/* Shift signed char three times right */
b = 0b10000000; // b is a negative number -128. The leftmost bit is a sign-bit
b = b >> 3;     // After the shif b holds the value 0b11110000.
In machine code there is usually two different kinds of shift operations available: arithmetic shift and logical shift. Logical shift fills always zeros, even when right shifting a negative number. Arithmetic shift behaves like in the example above. Unfortunately there is no logical shift operator in C.

To be continued.. maybe.

Last edited: