第十五章 位操作
编程练习
1.编写一个将二进制字符串转化为数字值的函数。也就是说,如果您有以下语句: char * pbin = \
那么您可以将pbin作为一个参数传送给该函数,使该函数返回一个int值25。
#include <>
int bin_dec(char *p);
char * pbin = \
int main(void) {
printf(\ return 0; }
int bin_dec(char *p) {
int dec=0; while(*p != '\\0')
dec = ( dec<<1 ) + *p++ - '0' ; return dec;
}
2.编写一个程序,该程序用命令行参数读取两个二进制字符串,并打印对每个数使用~运算符的结果,以及对这两个数使用&、|和^运算符的结果。使用二进制字符串形式显示结果。
#include <> #include <>
#define M 8*sizeof(int) + 1
char* extend(char *source, char *destination); char* reverse(char *destination, char *source);
char* and(char *destination, char *source1, char *source2); char* or(char *destination, char *source1, char *source2);
char* exclusive_or(char *destination, char *source1, char *source2);
int main(int argc,char *argv[]) {
char x[M],y[M],z[M];
printf(\ }
int comp(const void * p1, const void * p2) /* mandatory form */ {
/* get right type of pointer */
const struct names *ps1 = (const struct names *) p1; const struct names *ps2 = (const struct names *) p2; int res;
res = strcmp(ps1->last, ps2->last); /* compare last names */ if (res != 0) return res;
else /* last names identical, so compare first names */ return strcmp(ps1->first, ps2->first); }
7.下面是使用了可变函数的程序片断:
#include <> #include <> #include <>
void show_array(const double ar[], int n); double * new_d_array(int n, ...);
int main() {
double * p1; double * p2;
p1 = new_d_array(5, , , , , ; p2 = new_d_array(4, , , , ; show_array(p1, 5); show_array(p2, 4); free(p1); free(p2);
return 0; }
new_d_array()函数接受一个iit参数和数量可变的double参数。该函数返回一个指向malfoc()分配的内存块的指针。int参数指定动态数组中的元素个数:double值用于初始化元素(第个值赋予第一个元素,依此类推)。提供show_array()和new_d_array()的代码,使程序完整。
#include <> #include <> #include <>
void show_array(const double ar[], int n); double * new_d_array(int n, ...);
int main() {
double * p1; double * p2;
p1 = new_d_array(5, , , , , ; p2 = new_d_array(4, , , , ; show_array(p1, 5); show_array(p2, 4);
free(p1); free(p2);
return 0; }
void show_array(const double ar[], int n) { int i;
for(i=0; i double * new_d_array(int n, ...) { double *p; int i; va_list ap; p = (double *) malloc(n*sizeof(double)); va_start(ap, n); for(i=0; i p[i] = va_arg(ap, double); va_end(ap); return p; } 第17章 高级数据表示 (上) 编程练习 1.修改程序清单,使其既能以正序又能以逆序显示电影列表。一种方法是修改链表定义以使链表能被双向遍历;另一种方法是使用递归。 #include <> #include <> #include <> #define TSIZE 45 struct movie{ char name[TSIZE]; int rating; struct movie *next; struct movie *former; }; void CreateMovies(struct movie **phead, struct movie **pend); void DisplayOriginal(struct movie *head, struct movie *end); void DisplayReverse(struct movie *head, struct movie *end); void FreeMoives(struct movie *head, struct movie *end); int main(void) { struct movie *head = NULL, *end = NULL; CreateMovies(&head ,&end); DisplayOriginal(head,end); DisplayReverse(head,end); FreeMoives(head,end); return 0; } void CreateMovies(struct movie **phead, struct movie **pend) {