This is very tricky, extremely low-level stuff. Are you absolutely sure you cannot solve this in any other way? Have you taken endianness into account? You are? You have? OK.
C++ does not allow you to take a contiguous region in memory and interpret it as anything you want. Pretty much the only thing you are allowed to do is to interpret a pointer to the beginning of a contiguous block of memory that belongs to one single array as a char*
, unsigned char*
or since C++17 also std::byte*
(see strict aliasing rules, section [basic.lval] in the Standard, for C++17 it’s § 6.10 (8)). Essentially that means you can interpret an array as a sequence of bytes. That’s it, but it’s enough to copy the memory around. And that’s how you convert between unrelated types.
Using C-style arrays (they are error prone, so avoid if possible):
#include <cstddef>
#include <cstdint>
#include <cstring>
int main()
{
constexpr std::size_t item_count = 10;
float float_array[item_count] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::uint16_t int_array[item_count * (sizeof(float) / sizeof(uint16_t))];
std::memcpy(
reinterpret_cast<char*>(int_array),
reinterpret_cast<char*>(float_array),
item_count * sizeof(float));
}
Or with std::array
:
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
int main()
{
std::array<float, 10> float_array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<std::uint16_t, float_array.size() * (sizeof(float) / sizeof(uint16_t))> int_array;
std::memcpy(
reinterpret_cast<char*>(int_array.data()),
reinterpret_cast<char*>(float_array.data()),
float_array.size() * sizeof(float));
}