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

后端 未结 3 1053
无人及你
无人及你 2021-01-13 16:28

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 w

3条回答
  •  忘掉有多难
    2021-01-13 16:49

    Just do a reinterpret cast of the respective memory location:

    float f = 0.5f;
    unsigned int i = *reinterpret_cast(&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.

提交回复
热议问题