Program Listing for File endianness_wrappers.hpp
↰ Return to documentation for file (src/tap/architecture/endianness_wrappers.hpp
)
/*
* Copyright (c) 2020-2021 Advanced Robotics at the University of Washington <robomstr@uw.edu>
*
* This file is part of Taproot.
*
* Taproot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Taproot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Taproot. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef TAPROOT_ENDIANNESS_WRAPPERS_HPP_
#define TAPROOT_ENDIANNESS_WRAPPERS_HPP_
#include <cstdint>
#include <cstring>
#include "modm/architecture/detect.hpp"
namespace tap
{
namespace arch
{
template <typename T>
inline void dataToByteArray(T data, uint8_t *bytesOut, bool forward)
{
int numBytes = sizeof(T);
for (int i = 0; i < numBytes; i++)
{
int index = forward ? i : numBytes - 1 - i;
uint8_t byte = (data >> (8 * index)) & 0xff;
bytesOut[i] = byte;
}
}
template <typename T>
inline void byteArrayToData(T *data, const uint8_t *bytesIn, bool forward)
{
int numBytes = sizeof(T);
for (int i = 0; i < numBytes; i++)
{
int index = forward ? i : numBytes - 1 - i;
uint8_t byte = (*(bytesIn + index));
*(reinterpret_cast<uint8_t *>(data) + i) = byte;
}
}
template <typename T>
void convertToLittleEndian(T data, uint8_t *bytesOut)
{
#if MODM_IS_LITTLE_ENDIAN
memcpy(bytesOut, &data, sizeof(T));
#else
dataToByteArray(data, bytesOut, false);
#endif
}
template <typename T>
void convertToBigEndian(T data, uint8_t *bytesOut)
{
#if MODM_IS_LITTLE_ENDIAN
dataToByteArray(data, bytesOut, false);
#else
memcpy(bytesOut, &data, sizeof(T));
#endif
}
template <typename T>
void convertFromLittleEndian(T *data, const uint8_t *bytesIn)
{
#if MODM_IS_LITTLE_ENDIAN
*data = *reinterpret_cast<const T *>(bytesIn);
#else
byteArrayToData(data, bytesIn, false);
#endif
}
template <typename T>
void convertFromBigEndian(T *data, const uint8_t *bytesIn)
{
#if MODM_IS_LITTLE_ENDIAN
byteArrayToData(data, bytesIn, false);
#else
*data = *reinterpret_cast<const T *>(bytesIn);
#endif
}
inline float bigEndianInt16ToFloat(const uint8_t *buff)
{
return static_cast<float>(static_cast<int16_t>((*(buff)) | (*(buff + 1) << 8)));
}
} // namespace arch
} // namespace tap
#endif // TAPROOT_ENDIANNESS_WRAPPERS_HPP_