I have a unsigned char*
. Typically this points to a chunk of data, but in some cases, the pointer IS the data, ie. casting a int
value to the unsigned char*
pointer (unsigned char* intData = (unsigned char*)myInteger;
), and vice versa.
However, I need to do this with a float
value, and it keeps giving me conversion errors.
unsigned char* data;
float myFloat = (float)data;
How can I do this?
bit_cast:
template <class Dest, class Source>
inline Dest bit_cast(Source const &source) {
static_assert(sizeof(Dest)==sizeof(Source), "size of destination and source objects must be equal");
static_assert(std::is_trivially_copyable<Dest>::value, "destination type must be trivially copyable.");
static_assert(std::is_trivially_copyable<Source>::value, "source type must be trivially copyable");
Dest dest;
std::memcpy(&dest, &source, sizeof(dest));
return dest;
}
Usage:
char *c = nullptr;
float f = bit_cast<float>(c);
c = bit_cast<char *>(f);
The only correct way to use a given variable to store other data is to copy the data byte-wise:
template <typename T>
void store(unsigned char * & p, T const & val)
{
static_assert(sizeof(unsigned char *) >= sizeof(T));
char const * q = reinterpret_cast<char const *>(&val);
std::copy(q, q + sizeof(T), reinterpret_cast<char *>(&p));
}
Usage:
unsigned char * p;
store(p, 1.5);
store(p, 12UL);
The matching retrieval function:
template <typename T>
T load(unsigned char * const & p)
{
static_assert(sizeof(unsigned char *) >= sizeof(T));
T val;
char const * q = reinterpret_cast<char const *>(&p);
std::copy(q, q + sizeof(T), reinterpret_cast<char *>(&val));
return val;
}
Usage:
auto f = load<float>(p);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With