From 2ce238984ca466ebb50070cf88d80244dc767774 Mon Sep 17 00:00:00 2001 From: Matteo Cypriani Date: Thu, 7 Apr 2011 14:31:31 +0200 Subject: [PATCH] [lib] Add float endianess converters --- libowlps/libowlps.c | 29 +++++++++++++++++++++++++++++ libowlps/owlps.h | 12 ++++++++++++ 2 files changed, 41 insertions(+) diff --git a/libowlps/libowlps.c b/libowlps/libowlps.c index ad77de0..c11aea9 100644 --- a/libowlps/libowlps.c +++ b/libowlps/libowlps.c @@ -17,6 +17,8 @@ #include #include +#include + #define DEBUG @@ -237,6 +239,10 @@ owl_timestamp owl_time_elapsed(const owl_timestamp d1, } + +/* *** Endianess *** */ + + /* * Converts a owl_timestamp from host endianess to network endianess. */ @@ -261,6 +267,29 @@ owl_timestamp owl_ntoh_timestamp(const owl_timestamp d) } +/* + * Swap bytes composing a float. + * You probably want to use the macros owl_htonf() and owl_ntohf() + * instead of this function. + */ +float owl_swap_float(const float f) +{ + float ret ; + char + *f_bytes = (char*) &f, + *ret_bytes = (char*) &ret ; + + assert(sizeof(float) == 4) ; + + ret_bytes[0] = f_bytes[3] ; + ret_bytes[1] = f_bytes[2] ; + ret_bytes[2] = f_bytes[1] ; + ret_bytes[3] = f_bytes[0] ; + + return ret ; +} + + /* *** Network *** */ diff --git a/libowlps/owlps.h b/libowlps/owlps.h index a8dda9b..25e8700 100644 --- a/libowlps/owlps.h +++ b/libowlps/owlps.h @@ -252,8 +252,20 @@ uint_fast32_t owl_time_elapsed_ms(const owl_timestamp d1, const owl_timestamp d2) ; owl_timestamp owl_time_elapsed(const owl_timestamp d1, const owl_timestamp d2) ; + +// Endianess owl_timestamp owl_hton_timestamp(const owl_timestamp d) ; owl_timestamp owl_ntoh_timestamp(const owl_timestamp d) ; +float owl_swap_float(const float f) ; +#if __BYTE_ORDER == __BIG_ENDIAN +# define owl_htonf(f) (f) +# define owl_ntohf(f) (f) +#else // __BYTE_ORDER == __BIG_ENDIAN +# if __BYTE_ORDER == __LITTLE_ENDIAN +# define owl_htonf(f) owl_swap_float(f) +# define owl_ntohf(f) owl_swap_float(f) +# endif // __BYTE_ORDER == __LITTLE_ENDIAN +#endif // __BYTE_ORDER == __BIG_ENDIAN // Network int owl_create_udp_trx_socket(const char *const server_address,