endian.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include<__vic/endian.h>
  2. #include<iostream>
  3. #include<exception>
  4. #include<cstring>
  5. #include<cassert>
  6. namespace tests {
  7. //----------------------------------------------------------------------------
  8. const char *endian_str()
  9. {
  10. namespace endian = __vic::endian;
  11. switch(endian::native)
  12. {
  13. case endian::little: return "little";
  14. case endian::big: return "big";
  15. case endian::pdp: return "PDP";
  16. default: return "?";
  17. }
  18. }
  19. //----------------------------------------------------------------------------
  20. void run()
  21. {
  22. std::cout << "Endian is " << endian_str() << '\n';
  23. assert(__vic::swab16(0x0102) == 0x0201);
  24. assert(__vic::swab32(0x01020304) == 0x04030201);
  25. assert(__vic::swab64(0x0102030405060708) == 0x0807060504030201);
  26. const uint8_t bytes[4] = { 0x01, 0x02, 0x03, 0x04 };
  27. uint32_t n;
  28. std::memcpy(&n, bytes, 4);
  29. assert(__vic::endian::from_big(n) == 0x01020304);
  30. assert(__vic::endian::from_little(n) == 0x04030201);
  31. #if __cplusplus >= 201103L // C++11
  32. enum class En : uint32_t
  33. {
  34. be_value = 0x01020304,
  35. le_value = 0x04030201
  36. };
  37. En en;
  38. std::memcpy(&en, bytes, 4);
  39. assert(__vic::endian::from_big(en) == En::be_value);
  40. assert(__vic::endian::from_little(en) == En::le_value);
  41. #endif
  42. }
  43. //----------------------------------------------------------------------------
  44. } // namespace
  45. int main()
  46. {
  47. try
  48. {
  49. tests::run();
  50. return 0;
  51. }
  52. catch(const std::exception &ex)
  53. {
  54. std::cerr << ex.what() << '\n';
  55. }
  56. return 1;
  57. }