04-C Basics
04-C Basics
Jinyang Li
Lesson plan
• Overview
• C program organization
• Bitwise operators
• Control flow
C is an old programming language
C Java Python
1972 1995 2000 (2.0)
Procedure Object oriented Procedure & object oriented
Compiled to machine Compiled to bytecode, Scripting language, interpreted
code, runs directly on runs by another piece of by software
hardware software
int main()
{
printf("hello, world\n");
return 0;
A function “exported” by stdio.h
}
hello.c
test.c
Common compilation sequence
called
Source (Binary)
gcc –c main.c object linking
Code
main.c file (Binary)
main.o gcc main.o sum.o Executable
a.out
Source (Binary)
gcc –c
Code object
sum.c
sum.c file
sum.o
(Binary)
Source (Binary) gcc test.o sum.o –o test Executable
gcc –c test.c
Code object test
test.c file
test.o
Type Name
Primitive Types (64-bit machine)
if (a < b) {
printf("%d is smaller than %d\n", a, b);
} else if (a > b) {
printf("%d is larger than %d\n”, a, b);
}
return 0;
}
Compiler converts int types to the one with the larger value (e.g.
char à unsigned char à int à unsigned int)
int main()
{
int a = -1;
unsigned int b = 1;
if (a < (int) b) {
printf("%d is smaller than %d\n", a, b);
} else if (a > (int) b) {
printf("%d is larger than %d\n”, a, b);
}
return 0;
}
Operators
Arithmetic +, -, *, /, %, ++, --
Relational ==, !=, >, <, >=, <=
Logical &&, ||, !
Bitwise &, |, ^, ~, >>, <<
( 0 1 1 0 1 0 0 1 )2
& ( 0 1 0 1 0 1 0 1 )2
Result of 0x69 & 0x55
( 0 1 0 0 0 0 0 1 )2
Example use of &
int clear_msb(int x) {
return x & 0x7fffffff;
}
Bitwise OR: |
x y x OR y
0 0 0
0 1 1
1 0 1
1 1 1
( 0 1 1 0 1 0 0 1 )2
| ( 0 1 0 1 0 1 0 1 )2
Result of 0x69 | 0x55
( 0 1 1 1 1 1 0 1 )2
Example use of |
int set_msb(int x) {
return x | 0x80000000;
}
Bitwise NOT: ~
x NOT x
0 1
1 0
~ ( 0 1 1 0 1 0 0 1 )2
result of ~0x69
( 1 0 0 1 0 1 1 0 )2
Bitwise XOR: ^
x y x XOR y
0 0 0
0 1 1
1 0 1
1 1 0
( 0 1 1 0 1 0 0 1 )2
result of 0x69^0x55 ^ ( 0 1 0 1 0 1 0 1 )2
( 0 0 1 1 1 1 0 0 )2
Bitwise left-shift: <<
x << y, treat x as a bit-vector, shift x left by y positions
– Throw away bits shifted out on the left
– Fill in 0’s on the right
=(0 1 0 0 1 0 0 0)2
Bitwise right-shift: >>
=(0 0 0 1 0 1 0 1)2
int b = -1; ??
b = 3
b = b >>31;
a=0?? b=-1
??
Example use of shift