>> static_cast<float>(v[0])
You're casting an int to float. You need to cast the int* to a float* and then dereference.
>> inline void endian_swap(int& x) {
Be careful, though, as sizeof( int ) may not be 4.
>> You could probably turn it into a template pretty easily so it will swap the endiness of any size of int.
This should work with any POD:
Code:
inline bool little_endian( void )
{
typedef unsigned char* pbyte;
static unsigned long word = 0x1;
static bool is_little_endian_machine = ( *pbyte( &word ) == 0x1 );
return is_little_endian_machine;
}
inline bool big_endian( void )
{
return !little_endian( );
}
namespace detail {
template < typename Type >
Type& endian_conversion_dispatcher_( Type* value, bool little_endian_mode )
{
typedef unsigned char* pbyte;
if( little_endian( ) != little_endian_mode )
std::reverse( pbyte( value ), pbyte( value ) + sizeof( Type ) );
return *value;
}
template < typename Type >
inline Type endian_conversion_dispatcher_( Type const& value, bool little_endian_mode )
{
Type result = value;
return endian_conversion_dispatcher_( &result, little_endian_mode );
}
} // namespace detail
template < typename Type >
inline Type& little_endian( Type* value )
{
return detail::endian_conversion_dispatcher_( value, true );
}
template < typename Type >
inline Type little_endian( Type const& value )
{
return detail::endian_conversion_dispatcher_( value, true );
}
template < typename Type >
inline Type& big_endian( Type* value )
{
return detail::endian_conversion_dispatcher_( value, false );
}
template < typename Type >
inline Type big_endian( Type const& value )
{
return detail::endian_conversion_dispatcher_( value, false );
}
Another benefit here is that the template automatically detects the endianess of the machine it's running on, so that you don't have to change the user side of the code. So for instance, let's say you have a float value you want to store in a file in big-endian format. Right before the value is written to the file, it is passed through the big_endian function. Likewise, when the value is later read from a file, the big_endian function is used to convert it back. (Note that the functions that take no arguments are only for implementing certain optimizations, and needn't be used as logic during conversion.)