Course contentsShow
← C
Lesson 232 of 1,2193. Operators and ExpressionsFree lesson

Signed to unsigned conversion

Signed to unsigned conversion

What you'll learn: How C reinterprets the bits of a negative number when assigning it to an unsigned variable.

The Bit-Level "Suitcase"

Imagine you have a suitcase that can hold exactly 8 items. If you put a label on it that says "Signed," you agree that a full suitcase represents a negative number using a system called Two’s Complement. If you change the label to "Unsigned," you agree that the same physical contents now represent a large positive number.

In C, when you convert a signed integer to an unsigned integer, the underlying bits do not change at all. Instead, the computer simply stops treating the leftmost bit as a "negative sign" and starts treating it as a value-carrying digit.

The "Wrap-Around" Effect

Because unsigned types cannot represent negative values, C uses a mathematical "wrap-around" logic. If you try to force a -1 into an unsigned variable, it doesn't become 0; it wraps around to the largest possible value the variable can hold.

Think of it like a digital odometer on a car. If you are at 0000 and somehow drive backward one mile, the odometer rolls over to 9999. In C, converting -1 to an unsigned int results in the maximum possible value for that type (usually 4,294,967,295 on modern systems).

Seeing it in Code

Here is how this looks in practice. We take a negative number and "cast" it (force it) into an unsigned type:

#include <stdio.h>

int main() {
    int negative_val = -1;
    
    // Converting signed to unsigned
    unsigned int positive_val = (unsigned int)negative_val;

    printf("Signed value: %d\n", negative_val);
    printf("As unsigned:  %u\n", positive_val);

    return 0;
}

If you run this, the unsigned value will be a massive number. The bits haven't moved; only our "lenses" for looking at them have changed.

Why This Matters

This conversion happens automatically if you mix types in math (like 5 + -10u). C will silently convert the signed -10 into a massive unsigned number before doing the math, leading to results that look like bugs but are actually just the "wrap-around" logic in action. Always be cautious when your logic requires negative numbers to interact with unsigned variables.

Key takeaway

When converting signed to unsigned, the bit pattern stays the same, but negative values "wrap around" to become very large positive numbers.