[go: up one dir, main page]

An Embedded C Program

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 10

An Embedded C Program

1
Variable Types and Sizes
Type Size(Bits) Range
bit 1 0,1
char 8 -128 to 127
unsigned char 8 0 to 255
int 16 -32768 to 32767
short int 16 -32768 to 32767
unsigned int 16 0 to 65535
signed int 16 -32768 to 32767
long int 32
unsigned long int 32
signed long int 32
float 32 +-1.175e-38 to +-
3.4e38
double 32 +-1.175e-38 to +-
3.4e38
2
Constants
Numerical Constants
decimal 1234
binary 0b10101011
hexadecimal 0xff
octal 0777

Character Constants
character representation Equivalent Hex Value

TAB ‘\t’ ‘\x09’


LF (new line) ‘\n’ ‘\x0a’
CR ‘\r’ ‘\x0d’
Backspace ‘\b’ ‘\x08’
--
--
example printf(“c = %d\n”, c) //
printf(“c = %d\n\r”, c) // 3
Operators
Arithmetic Operators
Multiply * Beware division:
Divide / • If second argument is integer, the
Modulo % result will be integer (rounded):
Addition + 5 / 10  0 whereas 5 / 10.0  0.5
Subtraction - • Division by 0 will cause overflow
Negation -

Bitwise Operators
Ones complement ~
Left Shift <<
Right Shift >>
AND &
Exclusive OR ^
OR |

4
Bitwise Operations
Given an unsigned char y = 0xC9
operation result
x = ~y x = 0x36
x = y <<3 x = 0x48
x = y>>4 x = 0x0C
x = y&0x3F x = 0x09
x = y^1 x = 0xC8
x = y | 0x10 x = 0xD9

other examples:
unsigned char z
z = PINA & 0x06;
PORTB = PORTB | 0x60;
PORTB = PORTB & 0xfe;

5
Logical Operators
Logical operator
AND &&
OR ||

x =5 and y =2
(x && y) is true, because both are non-zero
(x & y) is false, because 00000101 bitwise AND 00000010 equal to zero

(x || y) is true, because either value is non-zero


(x | y) is true, b101 bitwise OR b010 is b111 (non-zero)

6
Division
Beware division:
• If second argument is integer, the
result will be integer (rounded):
5 / 10  0 whereas 5 / 10.0  0.5
• Division by 0 will cause a problem

7
Relational Operators
Relational Operators
Is Equal to ==
Is Not equal to !=
Less Than <
Less Than or Equal to <=
Greater than >
Greater Than or equal to >=
x = 3 and y =5
(x == y) FALSE
(x != y) TRUE
(x < y) TRUE
(x<=y) TRUE
(x>y) FALSE
(x >= y) FALSE 8
Data format
Conversion specifier Description

%d display as a signed decimal integer


%6d at least 6 characters wide
%u display as an unsigned decimal integer
%x display as an unsigned hexadecimal integer
%e display a floating point value in exponential
notation, such as 9.4567e2
%f display a floating point value in fixed point
notation, such as 945.67
%6f at least 6 characters wide
%.2f 2 characters after decimal point
%6.2f at least 6 characters wide and 2 after decimal
point

9
Assignment Operators
x = y assign y to x x += y assign (x+y) to x
x++ post-increment x x -= y assign (x-y) to x
++x pre-increment x x *= y assign (x*y) to x
x-- post-decrement x x /= y assign (x/y) to x
--x pre-decrement x x %= y assign (x%y) to x

int x=5; int x=5;


int y; int y;
y = ++x; y = x++;
/* x == 6, y == 6 */ /* x == 6, y == 5 */

10

You might also like