parity.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "parity.h"
  2. uint32_t __paritysi2(uint32_t a) {
  3. uint32_t x = (uint32_t)a;
  4. x ^= x >> 16;
  5. x ^= x >> 8;
  6. x ^= x >> 4;
  7. return (0x6996 >> (x & 0xF)) & 1;
  8. }
  9. static const uint8_t g_odd_byte_parity[256] = {
  10. 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,
  11. 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1,
  12. 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
  13. 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0,
  14. 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1,
  15. 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0,
  16. 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1,
  17. 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
  18. 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};
  19. #define ODD_PARITY8(x) \
  20. { g_odd_byte_parity[x] }
  21. #define EVEN_PARITY8(x) \
  22. { !g_odd_byte_parity[x] }
  23. uint8_t oddparity8(const uint8_t x) {
  24. return g_odd_byte_parity[x];
  25. }
  26. uint8_t evenparity8(const uint8_t x) {
  27. return !g_odd_byte_parity[x];
  28. }
  29. uint8_t evenparity16(uint16_t x) {
  30. #if !defined __GNUC__
  31. x ^= x >> 8;
  32. return EVEN_PARITY8(x);
  33. #else
  34. return (__builtin_parity(x) & 0xFF);
  35. #endif
  36. }
  37. uint8_t oddparity16(uint16_t x) {
  38. #if !defined __GNUC__
  39. x ^= x >> 8;
  40. return ODD_PARITY8(x);
  41. #else
  42. return !__builtin_parity(x);
  43. #endif
  44. }
  45. uint8_t evenparity32(uint32_t x) {
  46. #if !defined __GNUC__
  47. x ^= x >> 16;
  48. x ^= x >> 8;
  49. return EVEN_PARITY8(x);
  50. #else
  51. return (__builtin_parity(x) & 0xFF);
  52. #endif
  53. }
  54. uint8_t oddparity32(uint32_t x) {
  55. #if !defined __GNUC__
  56. x ^= x >> 16;
  57. x ^= x >> 8;
  58. return ODD_PARITY8(x);
  59. #else
  60. return !__builtin_parity(x);
  61. #endif
  62. }