Created
October 18, 2018 17:41
-
-
Save yisonPylkita/a1318b6d9ce75e5bbc8b1245340b8f76 to your computer and use it in GitHub Desktop.
Loading uint16_6 and uint32_t from little/big endian memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <cstdint> | |
#if !defined(__ORDER_LITTLE_ENDIAN__) | |
#error "Only little endian systems are supported" | |
#endif | |
// All of these functions are constexpr (c++11 compatibile and above) | |
// Generated code - https://godbolt.org/z/Tz7Wvg | |
namespace byte_converter { | |
constexpr uint16_t load_uint16_from_le(const uint8_t *raw_data) | |
{ | |
return ((uint16_t)(raw_data[1]) << 8) | (uint16_t)raw_data[0]; | |
} | |
constexpr uint16_t load_uint16_from_be(const uint8_t *raw_data) | |
{ | |
return ((uint16_t) (raw_data[0]) << 8) | (uint16_t) raw_data[1]; | |
} | |
constexpr uint32_t load_uint32_from_le(const uint8_t *raw_data) | |
{ | |
return (uint32_t)(raw_data[3]) << 24 | (uint32_t)raw_data[2] << 16 | (uint32_t)raw_data[1] << 8 | (uint32_t)raw_data[0]; | |
} | |
constexpr uint32_t load_uint32_from_be(const uint8_t *raw_data) | |
{ | |
return ((uint32_t)(raw_data[0]) << 24) | (uint32_t)raw_data[1] << 16 | (uint32_t)raw_data[2] << 8 | (uint32_t)raw_data[3]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment