1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <type_traits>
#include <cstring>
#include <iomanip>
template< typename T >
void write_bytes( const T* data, std::size_t n, void* dest ) {
static_assert( std::is_trivially_copyable<T>::value ) ;
const auto nbytes = sizeof(T)*n ;
std::memcpy( dest, data, nbytes ) ;
const unsigned char* pb = reinterpret_cast<const unsigned char*>(data) ;
std::cout << "bytes: " ;
for( std::size_t i = 0 ; i < nbytes ; ++i ) std::cout << std::setw(4) << int( pb[i] ) ;
std::cout << '\n' ;
}
template< typename T >
void read_bytes( const void* srce, T* data, std::size_t n ) {
static_assert( std::is_trivially_copyable<T>::value ) ;
const auto nbytes = sizeof(T)*n ;
std::memcpy( data, srce, nbytes ) ;
}
template< typename T, std::size_t N >
void write_bytes( const T (&data)[N], void* dest ) { write_bytes( data, N, dest ) ; }
template< typename T, std::size_t N >
void read_bytes( const void* srce, T (&data)[N] ) { read_bytes( srce, data, N ) ; }
int main() {
unsigned char buffer[1024] ;
int array[] { 1, 2, 3, 4, 5, 6 } ;
for( int v : array ) std::cout << v << ' ' ; // 1 2 3 4 5 6
std::cout << '\n' ;
static_assert( sizeof(buffer) >= sizeof(array) ) ;
write_bytes( array, buffer ) ; // save value representation into buffer
for( int& v : array ) v *= 23 ; // modify array
for( int v : array ) std::cout << v << ' ' ; // 23 46 69 92 115 138
std::cout << '\n' ;
read_bytes( buffer, array ) ; // restore saved value
for( int v : array ) std::cout << v << ' ' ; // 1 2 3 4 5 6
std::cout << '\n' ;
}
|