Convert pointer to float?

I have an unsigned char* . This usually indicates a piece of data, but in some cases, the IS pointer is data, i.e. casting an int value to an unsigned char* pointer ( unsigned char* intData = (unsigned char*)myInteger; ) and vice versa.

However, I need to do this using the float value, and it continues to give me conversion errors.

 unsigned char* data; float myFloat = (float)data; 

How can i do this?

+4
source share
4 answers

If your compiler supports it (GCC does), then use concatenation. This behavior is undefined according to the C ++ standard.

 union { unsigned char* p; float f; } pun; pun.p = data; float myFloat = pun.f; 

This works if sizeof(unsigned char *) == sizeof(float) . If pointers are more than floating, you need to rethink your strategy.

See the punning wikipedia article and, in particular, the union use section.

GCC allows you to use punning with union if you use union directly rather than typecasting in union ... see this IBM discussion on pun-type problems for the correct and incorrect ways to use GCC to customize types.

Also see the wikipedia article on strong and weak typing and a well-studied article on punning type and strict alias .

+2
source

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; } 

Using:

 char *c = nullptr; float f = bit_cast<float>(c); c = bit_cast<char *>(f); 
+4
source

The only correct way to use this variable to store other data is to copy the data byte by byte:

 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)); } 

Using:

 unsigned char * p; store(p, 1.5); store(p, 12UL); 

Matching search 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; } 

Using:

 auto f = load<float>(p); 
+3
source
 unsigned char* data; float myFloat = *(float*)data; 
-1
source

Source: https://habr.com/ru/post/1433910/


All Articles