Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pointer to float?

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?

like image 592
Noah Roth Avatar asked Feb 20 '23 04:02

Noah Roth


2 Answers

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);
like image 61
bames53 Avatar answered Feb 27 '23 04:02

bames53


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);
like image 43
Kerrek SB Avatar answered Feb 27 '23 04:02

Kerrek SB