ch20
ch20
Chapter 20
Low-Level Programming
Introduction
• Previous chapters have described C’s high-level,
machine-independent features.
• However, some kinds of programs need to
perform operations at the bit level:
– Systems programs (including compilers and operating
systems)
– Encryption programs
– Graphics programs
– Programs for which fast execution and/or efficient use
of space is critical
Bitwise Operators
• C provides six bitwise operators, which operate
on integer data at the bit level.
• Two of these operators perform shift operations.
• The other four perform bitwise complement,
bitwise and, bitwise exclusive or, and bitwise
inclusive or operations.
xor.c
/* Performs XOR encryption */
#include <ctype.h>
#include <stdio.h>
#define KEY '&'
int main(void)
{
int orig_char, new_char;
while ((orig_char = getchar()) != EOF) {
new_char = orig_char ^ KEY;
if (isprint(orig_char) && isprint(new_char))
putchar(new_char);
else
putchar(orig_char);
}
return 0;
}
Bit-Fields in Structures
• The bit-field techniques discussed previously can
be tricky to use and potentially confusing.
• Fortunately, C provides an alternative: declaring
structures whose members represent bit-fields.
Bit-Fields in Structures
• Example: How DOS stores the date at which a file
was created or last modified.
• Since days, months, and years are small numbers,
storing them as normal integers would waste
space.
• Instead, DOS allocates only 16 bits for a date,
with 5 bits for the day, 4 bits for the month, and 7
bits for the year:
Bit-Fields in Structures
• A C structure that uses bit-fields to create an
identical layout:
struct file_date {
unsigned int day: 5;
unsigned int month: 4;
unsigned int year: 7;
};
• A condensed version:
struct file_date {
unsigned int day: 5, month: 4, year: 7;
};
Bit-Fields in Structures
• The type of a bit-field must be either int,
unsigned int, or signed int.
• Using int is ambiguous; some compilers treat the
field’s high-order bit as a sign bit, but others don’t.
• In C99, bit-fields may also have type _Bool.
• C99 compilers may allow additional bit-field
types.
Bit-Fields in Structures
• A bit-field can be used in the same way as any
other member of a structure:
struct file_date fd;
fd.day = 28;
fd.month = 12;
fd.year = 8; /* represents 1988 */
• Appearance of the fd variable after these
assignments:
Bit-Fields in Structures
• The address operator (&) can’t be applied to a bit-
field.
• Because of this rule, functions such as scanf
can’t store data directly in a bit-field:
scanf("%d", &fd.day); /*** WRONG ***/
• We can still use scanf to read input into an
ordinary variable and then assign it to fd.day.
viewmemory.c
/* Allows the user to view regions of computer memory */
#include <ctype.h>
#include <stdio.h>
int main(void)
{
unsigned int addr;
int i, n;
BYTE *ptr;
printf("\n");
printf(" Address Bytes Characters\
n");
printf(" ------- ----------------------------- ----------\
n");
return 0;
}