Advertisement
Guest User

Untitled

a guest
Dec 8th, 2022
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | Software | 0 0
  1. #include <cstdint>
  2. #include <vector>
  3. #include <cstring>
  4. #include <fstream>
  5. #include <bit>
  6.  
  7. struct Header_t {
  8.     uint32_t field1;
  9.     uint16_t field2;
  10.     uint16_t field3;
  11. };
  12.  
  13. int main() {
  14.     std::ifstream file("abu.bin", std::ios::in | std::ios::binary);
  15.     std::streampos fileSize = 0x12345;
  16.     std::vector<uint8_t> buf(fileSize);
  17.     uint8_t* pBuf = buf.data();
  18.     file.read(reinterpret_cast<char*>(pBuf), fileSize); // (1)
  19.     Header_t header;
  20.     header = *reinterpret_cast<Header_t*>(pBuf);  // (2)
  21.     //              ^ v одно и тоже
  22.     header = *static_cast<Header_t*>(static_cast<void*>(pBuf)); // (3)
  23.     std::memcpy(&header, pBuf, sizeof(Header_t));             // (4)
  24.     header = *std::bit_cast<Header_t*>(pBuf);               // (5)
  25.     static_assert(std::is_trivial_v<Header_t> &&
  26.          std::is_standard_layout_v<Header_t>);
  27.     return 0;
  28. }
Tags: C++
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement