Signed and unsigned values
An unsigned value uses all its bits for the magnitude.
A signed value uses the top bit to show a negative value.
The same bits give two different values. Only the interpretation changes.
Try it
The bits 11111010, which read as 250 or as -6. Select a bit to change it. Change the bit width or the signed mode to see the effect.
Name or expression
ID0
ASCII
·
Binary
0b
0b11111010
Hex
0x
0xFA
Decimal
250
Shift
Name or expression
ID0
Binary
0b
Hex
0x
Decimal
ASCII
·
Shift
Sign
Bits
Endian
7
6
5
4
3
2
1
0
Worked example
Read the bits 11111010 in both modes:
- As an unsigned value, add the powers of two: 128 + 64 + 32 + 16 + 8 + 2. The result is 250.
- As a signed value, the top bit has the value 1. The value is therefore negative.
- Invert the bits and add 1: 00000110, which is 6.
- The signed value is -6.
Where this is used
A sensor reading is often signed, because a temperature or a speed goes below zero.
A status register is almost always unsigned, because each bit is a flag.
A wrong mode gives a large positive value in place of a small negative value.
Points to note
- An 8-bit unsigned value holds 0 to 255. An 8-bit signed value holds -128 to 127.
- A 32-bit unsigned value holds 0 to 4294967295. A 32-bit signed value holds -2147483648 to 2147483647.
- A comparison between a signed value and an unsigned value is a common source of defects. The compiler converts one of them first.
The full tool
The full editor holds many values at the same time. It also evaluates expressions across them, and it reads live values from a serial port.
Open the full editorQuestions
- Do the bits change when I change the mode?
- No. The bits stay the same. Only the value that you read from them changes.
- Which mode does a C int use?
- A plain int holds a signed value. Use unsigned int, or a type such as uint32_t, for an unsigned value.
- Why is the negative range one larger?
- Zero uses one code in the positive half. The negative half therefore holds one more value.