fork(1) download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. template <typename T, typename PtrType>
  5. class BitReinterpretType
  6. {
  7. public:
  8. explicit BitReinterpretType(PtrType* ptr) : m_ptr(ptr) {}
  9.  
  10. inline const T& operator=(const T& source)
  11. {
  12. std::memcpy(m_ptr, &source, sizeof(source));
  13. return source;
  14. }
  15.  
  16. inline operator T() const
  17. {
  18. T result;
  19. std::memcpy(&result, m_ptr, sizeof(result));
  20. return result;
  21. }
  22.  
  23. private:
  24. PtrType* m_ptr;
  25. };
  26.  
  27. template <typename T, typename PtrType>
  28. class BitReinterpretTypeConst
  29. {
  30. public:
  31. explicit BitReinterpretTypeConst(const PtrType* ptr) : m_ptr(ptr) {}
  32.  
  33. inline operator T() const
  34. {
  35. T result;
  36. std::memcpy(&result, m_ptr, sizeof(result));
  37. return result;
  38. }
  39.  
  40. private:
  41. const PtrType* m_ptr;
  42. };
  43.  
  44. template <typename T, typename PtrType>
  45. inline auto BitReinterpret(const PtrType* ptr) noexcept -> BitReinterpretTypeConst<T, PtrType>
  46. {
  47. return BitReinterpretTypeConst<T, PtrType>{ptr};
  48. }
  49.  
  50. template <typename T, typename PtrType>
  51. inline auto BitReinterpret(PtrType* ptr) noexcept -> BitReinterpretType<T, PtrType>
  52. {
  53. return BitReinterpretType<T, PtrType>{ptr};
  54. }
  55.  
  56. struct my_struct
  57. {
  58. int x;
  59. };
  60.  
  61. int main()
  62. {
  63. unsigned char data[20] = {0xff, 0xff, 0xff, 0xff, /*etc*/};
  64.  
  65. my_struct ms = BitReinterpret<my_struct>(data);
  66. std::cout << std::hex << ms.x <<std::endl;
  67.  
  68. ms.x = 123;
  69.  
  70. BitReinterpret<my_struct>(data) = ms;
  71. std::cout << std::hex << int(data[0]) <<std::endl;
  72. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
ffffffff
7b