Signed and unsigned numbers store values differently. Knowing their behavior helps avoid mistakes when working with small 8-bit microcontrollers.
0
0
Signed vs unsigned behavior on 8-bit MCU in Embedded C
Introduction
When reading sensor data that can be negative or positive.
When counting items that can never be negative, like button presses.
When performing arithmetic that might overflow or wrap around.
When optimizing memory on small devices by choosing the right number type.
Syntax
Embedded C
signed char a; // can hold -128 to 127 unsigned char b; // can hold 0 to 255
signed char stores negative and positive numbers.
unsigned char stores only zero and positive numbers.
Examples
Here,
a can hold negative value -10, b holds positive 250.Embedded C
signed char a = -10; unsigned char b = 250;
Assigning values outside the range causes overflow and unexpected results.
Embedded C
signed char a = 130; // Overflow example unsigned char b = 260; // Overflow example
Converting negative signed value to unsigned wraps around to a large positive number.
Embedded C
signed char a = -1; unsigned char b = (unsigned char)a; // b becomes 255 due to wrap-around
Sample Program
This program shows how signed and unsigned 8-bit values behave and convert between each other on an 8-bit MCU.
Embedded C
#include <stdio.h> int main() { signed char s = -1; unsigned char u = 255; printf("Signed s = %d\n", s); printf("Unsigned u = %u\n", u); unsigned char converted = (unsigned char)s; signed char converted_back = (signed char)u; printf("Converted signed -1 to unsigned: %u\n", converted); printf("Converted unsigned 255 to signed: %d\n", converted_back); return 0; }
OutputSuccess
Important Notes
On 8-bit MCUs, char is usually 8 bits, so ranges are limited.
Unsigned types wrap around from max to 0, signed types wrap from max positive to min negative.
Be careful when mixing signed and unsigned in calculations to avoid bugs.
Summary
Signed types store negative and positive numbers; unsigned store only positive.
8-bit signed char ranges from -128 to 127; unsigned char from 0 to 255.
Conversions between signed and unsigned can cause wrap-around effects.