parity.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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) {g_odd_byte_parity[x]}
  20. #define EVEN_PARITY8(x) {!g_odd_byte_parity[x]}
  21. uint8_t oddparity8(const uint8_t x) {
  22. return g_odd_byte_parity[x];
  23. }
  24. uint8_t evenparity8(const uint8_t x) {
  25. return !g_odd_byte_parity[x];
  26. }
  27. uint8_t evenparity16(uint16_t x) {
  28. #if !defined __GNUC__
  29. x ^= x >> 8;
  30. return EVEN_PARITY8(x);
  31. #else
  32. return (__builtin_parity(x) & 0xFF);
  33. #endif
  34. }
  35. uint8_t oddparity16(uint16_t x) {
  36. #if !defined __GNUC__
  37. x ^= x >> 8;
  38. return ODD_PARITY8(x);
  39. #else
  40. return !__builtin_parity(x);
  41. #endif
  42. }
  43. uint8_t evenparity32(uint32_t x) {
  44. #if !defined __GNUC__
  45. x ^= x >> 16;
  46. x ^= x >> 8;
  47. return EVEN_PARITY8(x);
  48. #else
  49. return (__builtin_parity(x) & 0xFF);
  50. #endif
  51. }
  52. uint8_t oddparity32(uint32_t x) {
  53. #if !defined __GNUC__
  54. x ^= x >> 16;
  55. x ^= x >> 8;
  56. return ODD_PARITY8(x);
  57. #else
  58. return !__builtin_parity(x);
  59. #endif
  60. }