C For Embedded Systems
C For Embedded Systems
C For Embedded Systems
1
Chapter Review
2
Sizes of Data Types
• three methods to find out the exact sizes of the data types:
1. Read the compiler manual.
2. Use pseudo function sizeof().
3. Use C99 data types.
3
Why should I care about which data type to
use?
• Performance
• Overflow
• coercion
4
Performance
• Using 64-bit data type for saving 32-bit variable will cause:
1. Waste RAM resource
2. Twice RAM access time
3. Additional arithmetic instructions
5
ANSI C (ISO C89) integer data types and their
ranges
Data type Size Range Min Range Max
char 1 byte -128 127
unsigned char 1 byte 0 255
short int 2 bytes -32,768 32,767
unsigned short int 2 bytes 0 65,535
int 4 bytes -2,147,483,648 2,147,483,647
unsigned int 4 bytes 0 4,294,967,295
long 4 bytes -2,147,483,648 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
long long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
unsigned long long 8 bytes 0 18,446,744,073,709,551,615
6
Overflow
7
Coercion
• If you write a statement with different operand data types for a binary
operation, the compiler will convert the smaller data type to the bigger data
type. These implicit data type is called coercion.
• The compiler may or may not give you warning when coercion occurs.
• If the variable is signed and the data sized is increased, the new bits are filled
with the sign bit (most significant bit) of the original value.
• When you assign a larger data type to a smaller data type variable, the
higher order bits will be truncated. 8
ISO C99 integer data types and their ranges
9
Bit-wise operators in C
10
Setting and Clearing (masking) bits
11
Testing bit with bit-wise operators in C
• When it is necessary to test a given bit to see if it is high or low, the unused
bits are masked and then the remaining data is tested.
• Example:
if (var1 & 0x20)
12
Bit-wise shift operation in C
13
Compound Operators
Instruction Its equivalent using
compound operators
a = a + 6; a += 6;
a = a – 23; a –= 23;
y = y * z; y *= z;
z = z / 25; z /= 25;
w = w | 0x20; w |= 0x20;
v = v & mask; v &= mask;
m = m ^ togBits; m ^= togBits;
14
Bit-wise operations using compound operators
• The majority of hardware access level code involves setting a bit or bits in a
register, clearing a bit or bits in a register, toggling a bit or bits in a register,
and monitoring the status bits. For the first three cases, the compound
operators are very suitable.
15
Using shift operator to generate mask
• One way to ease the generation of the mask is to use the left shift operator.
To generate a mask with bit n set to 1, use the expression: 1 << n
• If more bits are to be set in the mask, they can be “or” together. To generate
a mask with bit n and bit m set to 1, use the expression:
(1 << n) | (1 << m)
• register |= (1 << 6) | (1 << 1);
16
Setting the value in a multi-bit field
17