Advertisement
Guest User

Untitled

a guest
Nov 30th, 2015
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. using uint = unsigned int;
  4. constexpr uint kLength = 6;
  5. constexpr uint kHighBit = 1 << (kLength - 1);
  6. constexpr uint kTrim = ((1 << (kLength)) - 1);
  7.  
  8. inline void print_binary(uint v) {
  9. for (uint i = 1 << (kLength - 1); i != 0; i >>= 1) {
  10. cout << ((v & i) ? 1 : 0);
  11. }
  12. }
  13.  
  14. inline uint neg(uint v) {
  15. return ((~v) & kTrim) + 1;
  16. }
  17.  
  18. inline void shift(uint &h, uint &a, uint &low) {
  19. low = a & 1;
  20. a = (a >> 1) | ((h & 1) << (kLength - 1));
  21. h = (h >> 1) | (h & kHighBit);
  22. }
  23.  
  24. inline void show_operation(uint a, uint q, uint l, string reason) {
  25. print_binary(a);
  26. cout << '\t';
  27. print_binary(q);
  28. cout << '\t';
  29. cout << (l ? 1 : 0);
  30. cout << '\t';
  31. cout << reason;
  32. cout << endl;
  33. }
  34.  
  35. uint booth(uint q, uint m) {
  36. uint a = 0;
  37. uint l = 0;
  38. show_operation(a, q, l, "Initialization");
  39.  
  40. for (uint i = 0; i < kLength; ++i) {
  41. if ((q & 1) != l) {
  42. if (q & 1) {
  43. // 10 -> minus
  44. a += neg(m);
  45. a &= kTrim;
  46. show_operation(a, q, l, "A = A - M");
  47. } else {
  48. // 01 -> minus
  49. a += m;
  50. a &= kTrim;
  51. show_operation(a, q, l, "A = A + M");
  52. }
  53. }
  54.  
  55. shift(a, q, l);
  56. show_operation(a, q, l, "Shift");
  57. }
  58.  
  59. return (a << kLength) | q;
  60. }
  61.  
  62. void demo_booth(uint q, uint m) {
  63. cout << "Q = " << q << "(0b"; print_binary(q); cout << ")" << endl;
  64. cout << "M = " << m << "(0b"; print_binary(m); cout << ")" << endl;
  65. cout << "-M = " << "(0b"; print_binary(neg(m)); cout << ")" << endl;
  66. cout << endl << "Operation:" << endl;
  67. uint r = booth(q, m);
  68. cout << endl;
  69. cout << "Booth's Algorithm = " << r << endl;
  70. cout << "CPU = " << q * m << endl;
  71. }
  72.  
  73. int main(int argc, char **argv) {
  74. if (argc != 3) {
  75. cerr << "Usage: " << argv[0] << " A Q" << endl;
  76. cerr << "Example: " << argv[0] << " 23 19" << endl;
  77. return -1;
  78. }
  79.  
  80. int a, b;
  81. sscanf(argv[1], "%d", &a);
  82. sscanf(argv[2], "%d", &b);
  83. demo_booth(a, b);
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement