From d3c56f7a52e7edd8e976c754ed7986b2cf7b2733 Mon Sep 17 00:00:00 2001 From: Hugues Delorme Date: Thu, 24 Jan 2013 11:28:59 +0100 Subject: [PATCH] libc: improve encoding routines --- src/c/endian.c | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/c/endian.c b/src/c/endian.c index b2ddf78..52dac89 100644 --- a/src/c/endian.c +++ b/src/c/endian.c @@ -2,14 +2,6 @@ #include -#define _INTERNAL_FOUG_ENCODE_NUMERIC_LE(NUMERIC_TYPE) \ - union { \ - NUMERIC_TYPE as_numeric; \ - uint8_t as_bytes[sizeof(NUMERIC_TYPE)]; \ - } u; \ - u.as_numeric = val; \ - memcpy(bytes, u.as_bytes, sizeof(NUMERIC_TYPE)); - foug_endianness_t foug_host_endianness() { union { @@ -54,7 +46,8 @@ uint16_t foug_decode_uint16_be(const uint8_t* bytes) void foug_encode_uint16_le(uint16_t val, uint8_t* bytes) { - _INTERNAL_FOUG_ENCODE_NUMERIC_LE(uint16_t); + bytes[0] = val & 0xFF; + bytes[1] = (val >> 8) & 0xFF; } uint32_t foug_uint32_swap(uint32_t val) @@ -91,7 +84,10 @@ uint32_t foug_decode_uint32_be(const uint8_t* bytes) void foug_encode_uint32_le(uint32_t val, uint8_t* bytes) { - _INTERNAL_FOUG_ENCODE_NUMERIC_LE(uint32_t); + bytes[0] = val & 0xFF; + bytes[1] = (val >> 8) & 0xFF; + bytes[2] = (val >> 16) & 0xFF; + bytes[3] = (val >> 24) & 0xFF; } static foug_real32_t convert_real32(uint32_t val) @@ -106,6 +102,18 @@ static foug_real32_t convert_real32(uint32_t val) return u.as_float; } +static uint32_t convert_uint32(foug_real32_t val) +{ + union + { + uint32_t as_integer; + foug_real32_t as_float; + } u; + + u.as_float = val; + return u.as_integer; +} + foug_real32_t foug_decode_real32_le(const uint8_t* bytes) { return convert_real32(foug_decode_uint32_le(bytes)); @@ -123,5 +131,5 @@ foug_real32_t foug_decode_real32_be(const uint8_t* bytes) void foug_encode_real32_le(foug_real32_t val, uint8_t* bytes) { - _INTERNAL_FOUG_ENCODE_NUMERIC_LE(foug_real32_t); + foug_encode_uint32_le(convert_uint32(val), bytes); }