Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a float variable to an unsigned int variable, bit image, not cast

Tags:

c++

I know this is a bizarre thing to do, and it's not portable. But I have an allocated array of unsigned ints, and I occasionaly want to "store" a float in it. I don't want to cast the float or convert it to the closest equivalent int; I want to store the exact bit image of the float in the allocated space of the unsigned int, such that I could later retrieve it as a float and it would retain its original float value.

like image 704
user1020872 Avatar asked Jan 18 '23 03:01

user1020872


2 Answers

This can be achieved through a simple copy:

uint32_t dst;
float    src = get_float();

char * const p = reinterpret_cast<char*>(&dst);

std::copy(p, p + sizeof(float), reinterpret_cast<char *>(&src));

// now read dst

Copying backwards works similarly.

like image 167
Kerrek SB Avatar answered Jan 25 '23 23:01

Kerrek SB


Just do a reinterpret cast of the respective memory location:

float f = 0.5f;
unsigned int i = *reinterpret_cast<unsigned int*>(&f);

or the more C-like version:

unsigned int i = *(unsigned int*)&f;

From your question text I assume you are aware that this breaks if float and unsigned int don't have the same size, but on most usual platforms both should be 32-bit.

EDIT: As Kerrek pointed out, this seems to be undefined behaviour. But I still stand to my answer, as it is short and precise and should indeed work on any practical compiler (convince me of the opposite). But look at Kerrek's answer if you want a UB-free answer.

like image 38
Christian Rau Avatar answered Jan 25 '23 23:01

Christian Rau