Beginning C Programming for Engineers
Lecture 6: Bit Operations
- R. Lindsay Todd
Bit Operations – p. 1/19
Beginning C Programming for Engineers Lecture 6: Bit Operations R. - - PowerPoint PPT Presentation
Beginning C Programming for Engineers Lecture 6: Bit Operations R. Lindsay Todd Bit Operations p. 1/19 Place Value Numerals A numeral represents a number using some notation. Normal place value numerals: each place represents a power of
Bit Operations – p. 1/19
Bit Operations – p. 2/19
017 /* 1*8 + 7 = 15 */ 0234 /* 2*64 + 3*8 + 4 = 156 */ 019 /* Compilation error! */
Bit Operations – p. 3/19
0x11 /* 1*16 + 1 = 17 */ 0xA0 /* 10*16 + 0 = 160 */ 0xAB /* 10*16 + 11 = 171 */
Bit Operations – p. 4/19
1
#include <stdio.h>
2 3
int main() {
4
int val;
5
printf("Enter value: ");
6
scanf("%i", &val);
7
printf("Decimal: %d, %i\n", val, val);
8
printf("Octal: %o\n", val);
9
printf("Hex x X: %x, %X\n", val, val);
10
return 0;
11
}
Bit Operations – p. 5/19
Bit Operations – p. 6/19
Bit Operations – p. 7/19
Octal Bit pattern Decimal 1 1 1 2 1 2 3 1 1 3 4 1 4 5 1 1 5 6 1 1 6 7 1 1 1 7
Hexadecimal Bit pattern Decimal 1 1 1 2 1 2 3 1 1 3 4 1 4 5 1 1 5 6 1 1 6 7 1 1 1 7 8 1 8 9 1 1 9 A 1 1 10 B 1 1 1 11 C 1 1 12 D 1 1 1 13 E 1 1 1 14 F 1 1 1 1 15
Bit Operations – p. 8/19
Bit Operations – p. 9/19
Bit Operations – p. 10/19
1 1 1 37
1 1 1 1 1 1 246
1 1 36
1 1 1 1 1 1 1 247
1 1 1 1 1 211
1 1 1 1 1 218
37 && 246 → 1 37 || 246 → 1
Bit Operations – p. 11/19
1
#include <stdio.h>
2 3
int main() {
4
int x;
5
printf("Enter number: ");
6
scanf("%i", &x);
7
printf("Lowest 5 bits: %X\n", (x & 0x001F));
8
return 0;
9
}
Bit Operations – p. 12/19
1
#include <stdio.h>
2 3
int main() {
4
int x;
5
printf("Enter number: ");
6
scanf("%i", &x);
7
printf("Lowest 5 bits set: %X\n", (x | 0x001F));
8
return 0;
9
}
Bit Operations – p. 13/19
x
~0x1F
x&~0x1F
y
y&0x1F
(x&~0x1F)|(y&0x1F)
Bit Operations – p. 14/19
1
#include <stdio.h>
2 3
int main() {
4
int x, y;
5
printf("Enter number: ");
6
scanf("%i", &x);
7
printf("Replacement bits: ");
8
scanf("%i", &y);
9
printf("With new bits: %X\n",
10
(x & ~0x001F) | (y & 0x001F) );
11
return 0;
12
}
Bit Operations – p. 15/19
1
#include <stdio.h>
2 3
int main() {
4
int x;
5
printf("Enter number: ");
6
scanf("%i", &x);
7
printf("Toggle bits 4, 6: %X\n", (x ^ 0x0050));
8
return 0;
9
}
Bit Operations – p. 16/19
Bit Operations – p. 17/19
Bit Operations – p. 18/19
1
/* Get an integer, extract bits 8-10.
2
* LSB is bit 0.
3
*/
4 5
#include <stdio.h>
6 7
int
8
main()
9
{
10
int i;
11 12
printf("Enter number: ");
13
scanf("%i", &i);
14
printf("i=%x\n", i);
15
printf("i>>8=%x\n", i>>8);
16
printf("Bits 8-10: %x\n", (i >> 8) & 07);
17
return 0;
18
}
Bit Operations – p. 19/19