endian.cpp 1.7 KB

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