ghash.h 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. struct ghash
  2. {
  3. static std::tuple<int,int> decode(unsigned h)
  4. {
  5. const unsigned S=0x80000000;
  6. int x=0,y=0;
  7. for(int i=0;i<16;i++)
  8. {
  9. x<<=1;
  10. y<<=1;
  11. if(h&S)
  12. x|=1;
  13. h<<=1;
  14. if(h&S)
  15. y|=1;
  16. h<<=1;
  17. }
  18. return std::make_tuple(x-32768,y-32768);
  19. }
  20. static unsigned encode(int x, int y)
  21. {
  22. return encode_(x+32768,y+32768);
  23. }
  24. public: //test
  25. static void test_code(int x,int y)
  26. {
  27. unsigned h=ghash::encode(x,y);
  28. auto t=ghash::decode(h);
  29. printf("src x=%X,y=%X hash=%X,check x=%X,y=%X\n",x,y,h,std::get<0>(t),std::get<1>(t));
  30. }
  31. static void test()
  32. {
  33. for(int i=0;i<10;i++)
  34. {
  35. test_code((4<<i)-1,(4<<i)-1);
  36. test_code((4<<i)-1,(4<<i));
  37. test_code((4<<i)-1,(4<<i)-1);
  38. test_code((4<<i),(4<<i)-1);
  39. }
  40. }
  41. private:
  42. static unsigned encode_(unsigned short x, unsigned short y)
  43. {
  44. const unsigned S=0x8000;
  45. unsigned r=0;
  46. for(int i=0;i<16;i++)
  47. {
  48. r<<=2;
  49. if(x&S)
  50. {
  51. r|=(y&S)?3:2;
  52. }
  53. else
  54. {
  55. if(y&S) r|=1;
  56. }
  57. x<<=1;
  58. y<<=1;
  59. }
  60. return r;
  61. }
  62. };