Search code examples
c#unsafe

In int to float unsafe conversion, what's does *(float*) (&num) do?


I am writing a stream API and it uses a lot of stuff that has to deal with BigEndian/LittleEndian and unsigned vs signed conversions. I have the following code, which does work. But I want to know what it's doing, can some ELI5 (explain like I am 5) please?

int num = ReadInt();
return *(float*) (&num);

 public int ReadInt()
        {
            return 
                (_memoryStream.ReadByte() << 0x18) |
                (_memoryStream.ReadByte() << 0x10) |
                (_memoryStream.ReadByte() << 0x08) |
                _memoryStream.ReadByte();
        }

Now I get what ReadInt does, it's simply turning a LittleEndian into BigEndian. The part that I can't seem to wrap my head around is the *(float*)(&num).

I am guessing it doing some memory shifting of some sort, but not 100% on that.


Solution

  • &num -- "the address of num", which is a pointer to an integer.

    (float*)&num - "the address of num, converted to a pointer to float."

    This is the memory address of num, but the compiler will interpret its content as a floating-point number, not an integer.

    *(float*)&num - The content of "the address of num, converted to a pointer to float" - in other words, take the memory occupied by num and read that out as a floating point number.

    So if you were to read in the bytes 0x40, 0x10, 0x00, 0x00, you'd get the integer 0x40100000 = 1074790400 in the memory location 'num' The address of 'num' would be converted to a pointer to float, and you'd pull the content of that. The constant 0x40100000, when interpreted as a float, is 2.25, which is what you'll return.