# Thread: Converting X,Y coords from a float into a DWORD?

1. ## Converting X,Y coords from a float into a DWORD?

Hey guys, I have the following packet containing the X and Y coordinates of an entity:
[66 96 5B 45] [9A D9 03 44]
X ___________Y

* they are in 32 bit float format

Code:
```int main()
{
const BYTE pkt[]={0x66, 0x96, 0x5B, 0x45, 0x9A, 0xD9, 0x03, 0x44};

////// *** not works: return wrong values
DWORD px = *(DWORD*)&pkt[0];
DWORD py = *(DWORD*)&pkt[4];
float fx = (float)px;
float fy = (float)py;
//////

////// *** works: it returns the correct values
float fx = *(float*)&pkt[0];
float fy = *(float*)&pkt[4];
//////

DWORD ix = (DWORD)fx;
DWORD iy = (DWORD)fy;

return 0;
}```
Why one works and the other doesn't?

2. In first case, you just cast integer value 1163630182 (px) to float... so
Code:
`float fx = (float)px;`
will return exactly 1163630182 but as float type.

this will return correct float values from your array
Code:
```	DWORD px = *(DWORD*)&pkt[0];
DWORD py = *(DWORD*)&pkt[4];
float fx = *((float*)&px);
float fy = *((float*)&py);```

3. ## The Following User Says Thank You to Grooguz For This Useful Post:

4. Ah ok, so I need to treat the DWORD variable as a pointer to a float number to be able to cast it to a float var.
Thanks for clarifying!

5. Another variant of conversion. We can use Unions to map the same memory (values) as multiple types.
Code:
```	union F2D {
DWORD dwVal;
FLOAT fVal;
};

F2D fThis;

const BYTE pkt[]={0x66, 0x96, 0x5B, 0x45, 0x9A, 0xD9, 0x03, 0x44};

////// *** #3 variant
fThis.dwVal = *(DWORD*)&pkt[0];
float fx = fThis.fVal;

fThis.dwVal = *(DWORD*)&pkt[4];
float fy = fThis.fVal;```

6. ## The Following User Says Thank You to Grooguz For This Useful Post:

7. Excelent, using unions is a nicer way to play with the coordinates. Thanks very much for the idea!

---------- Post added 2011-12-08 at 05:35 AM ---------- Previous post was 2011-12-01 at 08:59 PM ----------

Code:
```#include<stdio.h>
typedef unsigned int DWORD;

void dump(unsigned char* buf, int size)
{
for(int i=0;i<size;i++)
printf("%02X ", buf[i]);
printf("\n");
}

int main()
{
unsigned char pkt[]={0x66, 0x96, 0x5B, 0x45};   //=3513

DWORD dx = *(DWORD*)&pkt[0];
float fx = *(float*)&dx;
dump((unsigned char*)&fx,sizeof(fx));

DWORD dx2 = 3513;
float fx2 = *(float*)&dx2;
dump((unsigned char*)&fx2,sizeof(fx2));

return 0;
}

//    output:
//      fx   = 66 96 5B 45
//      fx2 = A8 C3 FD BF```
As you can see I got another sequence of bytes different from the original input {0x66, 0x96, 0x5B, 0x45}. How to make it work properly?