fork download
  1. #include <iostream>
  2. #include <cstdint>
  3. #include <bitset>
  4. #include <cstring>
  5. #include <algorithm>
  6.  
  7. struct bits
  8. {
  9. unsigned sender : 16 ;
  10. unsigned res : 16 ;
  11. unsigned e : 12 ;
  12. unsigned f : 4 ;
  13. };
  14.  
  15. int main()
  16. {
  17. const bits b { 0xffff, 3, 2, 1 } ;
  18.  
  19. const std::uint32_t res = b.res ;
  20. const std::uint32_t e = b.e ;
  21. const std::uint32_t f = b.f ;
  22.  
  23. std::uint32_t buff = ( res << 16 ) | ( e << 4 ) | f ;
  24. // test it
  25. std::cout << std::bitset<32>(buff) << '\n' ;
  26.  
  27. // copy it
  28. std::uint8_t byte_buff[4] ;
  29. std::memcpy( byte_buff, &buff, sizeof(buff) ) ;
  30.  
  31. // check endianness
  32. for( std::uint8_t b : byte_buff ) std::cout << std::bitset<8>(b) << ' ' ;
  33. std::cout << '\n' ;
  34.  
  35. // if needed, swap bytes
  36. std::swap( byte_buff[0], byte_buff[3] ) ;
  37. std::swap( byte_buff[1], byte_buff[2] ) ;
  38.  
  39. for( std::uint8_t b : byte_buff ) std::cout << std::bitset<8>(b) << ' ' ;
  40. std::cout << '\n' ;
  41. }
  42.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
00000000000000110000000000100001
00100001 00000000 00000011 00000000 
00000000 00000011 00000000 00100001