Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. /*
  2. The purpose of this function is to convert an unsigned
  3. binary number to reflected binary Gray code.
  4.  
  5. The operator >> is shift right. The operator ^ is exclusive or.
  6. */
  7. unsigned int binaryToGray(unsigned int num)
  8. {
  9. return (num >> 1) ^ num;
  10. }
  11.  
  12. /*
  13. The purpose of this function is to convert a reflected binary
  14. Gray code number to a binary number.
  15. */
  16. unsigned int grayToBinary(unsigned int num)
  17. {
  18. unsigned int mask;
  19. for (mask = num >> 1; mask != 0; mask = mask >> 1)
  20. {
  21. num = num ^ mask;
  22. }
  23. return num;
  24. }
  25.  
  26. unsigned int nextGray(unsigned int num)
  27. {
  28. return binaryToGray((grayToBinary(num) + 1) & 0x3F);
  29. }
  30.  
  31. unsigned int prevGray(unsigned int num)
  32. {
  33. return binaryToGray((grayToBinary(num) - 1) & 0x3F);
  34. }
  35.  
  36. unsigned next_gray(unsigned gray)
  37. {
  38. if (is_gray_odd(gray))
  39. {
  40. unsigned y = gray & -gray;
  41. return gray ^ (y << 1);
  42. }
  43. else
  44. {
  45. // Flip rightmost bit
  46. return gray ^ 1;
  47. }
  48. }
  49.  
  50. bool is_gray_odd(unsigned gray)
  51. {
  52. // A gray code is odd when the number
  53. // of bits set in its representation
  54. // is odd
  55. // If you have a popcount function
  56. // available, use it instead of the
  57. // following manual one
  58.  
  59. unsigned nb_bits = 0u;
  60. for (; gray ; ++nb_bits)
  61. {
  62. // clear the least significant bit set
  63. gray &= gray - 1;
  64. }
  65. return (bool)(nb_bits % 2);
  66. }
  67.  
  68. bool is_gray_odd(unsigned gray)
  69. {
  70. return (bool) __builtin_parity(gray);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement