[原创] 位运算和bit位操作程序题 -- 谭浩强C语言习题答案

这两天复习RenMian给我留下谭浩强的C语言教程,温故而知新,夯实基础知识,

把谭浩强版C语言的第十二章《位运算》的书复习后把所有的编程习题做了一遍,贴出来激励自己一下,也希望有用的同学可以参考,时间和水平有限,不足之处,恳请读者批评指正

第十二章《位运算》答案如下

inc/testBits.h

01.unsigned short getbits(unsigned short value, int n1, int n2)

02.{

03. unsigned short usRet = 0, usTemp = 0, usMask = 0;

04.

05. usTemp = value >> n1;

06. usMask = ~( ~0 << (n2 – n1 + 1));

07.

08. usRet = usTemp & usMask;

09.

10. return usRet;

11.}

12.

13.short getComplement(short n)

14.{

15. short sRet = 0;

16.

17. if (n >= 0)

18. {

19. sRet = n;

20. }

21. else

22. {

23. sRet = -n;

24. sRet = ~sRet;

25. sRet = sRet + 1;

26. }

27.

28. return sRet;

29.}

30.

31.unsigned short move(unsigned short value, int n)

32.{

33. unsigned short usTemp = 0, usDest = 0;

34.

35. assert(n != 0);

36.

37. if (n > 0)

38. {

39. usTemp = value << (16 -n);

40. usDest = value >> n;

41. }

42. else

43. {

44. n = -n;

45.

46. usTemp = value >> (16 – n);

47. usDest = value << n;

48. }

49.

50. usDest = usDest | usTemp;

51. return usDest;

52.}

53.

54.int test_12_1()

55.{

56. unsigned short usRet = 0;

57. usRet = getbits(0x83BD, 4, 7);

58.

59. if (usRet == 0xB)

60. {

61. printf(“Test_12_1 Passed! \r\n”);

62. return 0;

63. }

64.

65. return 1;

66.}

67.

68.int test_12_2()

69.{

70. int ite = 0, iRet = 0;

71. unsigned short usDest = 0, usSrc = 0xFFFF, usMask = 0;

72.

73. for(ite = 0; ite < 16; ite += 2)

74. {

75. usMask = 1 << ite;

76. usDest = usDest | (usSrc & usMask);

77. }

78.

79. if (usDest == 0x5555)

80. {

81. printf(“Test_12_2 Passed! \r\n”);

82. return 0;

83. }

84.

85. return 1;

86.}

87.

88.int test_12_4()

89.{

90. unsigned short usDest1 = 0, usDest2 = 0, usSrc = 0xFFF7;

91.

92. usDest1 = move(0xFFF7, 4);

93. usDest2 = move(0xFFF7, -4);

94.

95. if (usDest1 == 0x7FFF && usDest2 == 0xFF7F)

96. {

97. printf(“Test_12_4 Passed! \r\n”);

98. return 0;

99. }

100. return 1;

101.}

102.

103.int test_12_5()

104.{

105. short sDest = 0, sSrc = -10;

106.

107. sDest = getComplement(sSrc);

108.

109. if (sDest == 0xFFFFFFF6)

110. {

111. printf(“Test_12_5 Passed! \r\n”);

112. return 0;

113. }

114.

115. return 1;

116.}

117.

118.

119.int testBits()

120.{

121. int iRet = 0;

122.

123. iRet += test_12_1();

124. iRet += test_12_2();

125. iRet += test_12_4();

126. iRet += test_12_5();

127.

128. return iRet;

129.}

src/main.cc

01.#include <stdio.h>

02.#include <stdlib.h>

03.#include <assert.h>

04.

05.#include “../inc/testFile.h”

06.#include “../inc/testBits.h”

07.

08.int main()

09.{

10. int iRet = 0;

11.

12.#if 0

13. iRet += testFile();

14. assert(iRet == 0);

15.#endif

16.

17. iRet += testBits();

18. assert(iRet == 0);

19.

20. return 0;

21.}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/asiainfolf/archive/2011/03/19/6261765.aspx

    原文作者:位运算
    原文地址: https://www.cnblogs.com/sohu2000000/archive/2011/03/20/1989193.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞