Programming in C

(Barry) #1
Exercises 297

Exercises



  1. Type in and run the four programs presented in this chapter. Compare the output
    produced by each program with the output presented after each program in the
    text.

  2. Write a program that determines whether your particular computer performs an
    arithmetic or a logical right shift.

  3. Given that the expression ~0produces an integer that contains all 1s, write a func-
    tion called int_sizethat returns the number of bits contained in an inton your
    particular machine.

  4. Using the result obtained in exercise 3, modify the rotatefunction from Program
    12.4 so that it no longer makes any assumptions about the size of an int.

  5. Write a function called bit_testthat takes two arguments: an unsigned intand
    a bit number n.Have the function return 1 bit number nif it is on inside the
    word,and 0 if it is off. Assume that bit number 0 references the leftmost bit inside
    the integer. Also write a corresponding function called bit_setthat takes two
    arguments: an unsigned intand a bit number n.Have the function return the
    result of turning bit non inside the integer.

  6. Write a function called bitpat_searchthat looks for the occurrence of a speci-
    fied pattern of bits inside an unsigned int.The function should take three argu-
    ments and should be called as shown:
    bitpat_search (source, pattern, n)


The function searches the integer source,starting at the leftmost bit, to see if the
rightmost nbits of patternoccur in source. If the pattern is found, have the
function return the number of the bit at which the pattern begins, where the left-
most bit is bit number 0. If the pattern is not found, then have the function return
–1.So, for example, the call
index = bitpat_search (0xe1f4, 0x5, 3);

causes the bitpat_searchfunction to search the number 0xe1f4( = 1110 0001
1111 0100 binary ) for the occurrence of the three-bit pattern 0x5 (= 101 binary).
The function returns 11 to indicate that the pattern was found in the source
beginning with bit number 11.
Make certain that the function makes no assumptions about the size of an int(see
exercise 3 in this chapter).


  1. Write a function called bitpat_getto extract a specified set of bits. Have it take
    three arguments: the first an unsigned int, the second an integer starting bit
    number, and the third a bit count. Using the convention that bit numbering starts

Free download pdf