misc.h 878 B

12345678910111213141516171819202122232425262728293031
  1. #ifndef INCLUDE_MISC_H
  2. #define INCLUDE_MISC_H
  3. #include <cstdint>
  4. #define UNUSED(expr) (void)(expr)
  5. #define abs(x) ((x) < 0 ? -(x) : (x))
  6. #define min(a, b) (((a) < (b)) ? (a) : (b))
  7. #define max(a, b) (((a) > (b)) ? (a) : (b))
  8. #define in_range(x, a, b) (((x) >= (a)) && ((x) < (b)))
  9. /**
  10. * Read big endian integer value in binary data array. Depends on the size
  11. * of the given type, so using standardized types like stdint's is highly
  12. * suggested.
  13. *
  14. * Also doesn't check for being in bounds of the array.
  15. */
  16. template <typename T> T read_big_endian_value(const void *ptr)
  17. {
  18. T result = 0;
  19. uint8_t *data = (uint8_t *) ptr;
  20. // No, memcpy isn't working here because endianness issues.
  21. for (unsigned i = 0; i < sizeof(T); i++)
  22. // Writing each byte of value in order
  23. result |= data[i] << (8 * (sizeof(T) - 1 - i));
  24. return result;
  25. }
  26. #endif