Sei sulla pagina 1di 1

Prof. M.

Mansour American University of Beirut Spring 2009


Department of Electrical and Computer Engineering
EECE 321 – Computer Organization

Homework 1 (Due Friday Feb. 20, 2009)

Problem 1 [Short Questions]: Read Ch. 1 (P&H), then answer exercise 1.1.

Problem 2 [C Program]: Consider the following C program. It contains some bugs in it. Your task is to correct these
bugs, compile it and discover what it does. Return the corrected program on a CD with a short description about it.

#include <stdio.h>

int main ( ) {
unsigned int numToPrintInBase2 = 1431655765; /* alternating 1’s & 0’s */
unsigned int exp = 1;
int k; /* can't declare variable in a loop header */

/* Compute the highest storable power of 2 (2 to the 31th).*/


for (k=0; k<31; k++) {
exp = exp * 2;
}

/* For each power of 2 from the highest to the lowest,


print 1 if it occurs in the number, 0 otherwise. */

for (k=31; !(k=0); k--) {


if (numToPrintInBase2 >= exp) {
printf ("%d", '1');
numToPrintInBase2 = numToPrintInBase2 - exp;
}
else {
printf ("%d", '0');
}
exp = exp / 2;
}
printf ("\n");
return 0;
}

Problem 3 [Writing a C Program]: Write a function named CountBits that returns the number of 1-bits in the binary
representation of its unsigned integer argument. Add your function to the following program, and run the completed
program.

#include <stdio.h>

int CountBits (unsigned int n);

int main ( ) {
printf ("# 1-bits in base 2 rep of %u = %d, should be 1\n", 1, CountBits (1));
printf ("# 1-bits in base 2 rep of %u = %d, should be 31\n", 0xFFFFFFFF-1, CountBits(0xFFFFFFFF-1));
printf ("# 1-bits in base 2 rep of %u = %d, should be 6\n", 2334, CountBits(2334));
printf ("# 1-bits in base 2 rep of %u = %d, should be 12\n", 65520, CountBits(65520));
printf ("# 1-bits in base 2 rep of %u = %d, should be 14\n", 61423, CountBits(61423));
/* Your bit count function goes here. */

Potrebbero piacerti anche