Since no one mentioned sprintf
you can just convert any variable to char*
with it and send
if(strcmp(buf,"movUP") == 0) { char* msg = calloc(1, 20); pos.y += 0.0001f; sprintf(msg,"NEW::POS::Y=%.4f", pos.y); sendto(master, msg, 20, 0, (struct sockaddr*)&client, addrlen); }
Test
movUP NEW::POS::Y=0.0001 movUP NEW::POS::Y=0.0002 movUP NEW::POS::Y=0.0003 movUP NEW::POS::Y=0.0004
Use %d
for integers, %f
for floats
to convert back to integer, use atoi(char*)
to convert back to float, use atof(char*)
before conversion, be sure to use strstr()
to get the float value only starting at "0"
float myPos; // floating variable that stores Object Position in the World ... .... memset(buf, 0, MAXBUFFER); // clears the previous buffer recvfrom(master, buf, MAXBUFFER, 0, (struct sockaddr*)&server, &addrlen); char* newY = strstr(buf, "0");// NEW::POS::Y=0.0001 --->> 0.000100 myPos = atof(newY); // new object position by the server printf("My New Position is %.4f\n", myPos); // Out: My New Position is 0.0011 -> 0.0012 -> 0.0013 -> 0.0014.
For integers ( not ) you can use the same technique and just multiply it by
float f = 0.000002f; // that is supposed to be 2 integer value int i = (int)(f*1000000); // now, i = 2
the above methods are fully protected
If you want a harder conversion, you can use strncpy
or memcpy
and cut the line starting at the given index with some length, assuming you already know the incoming buffer, but in my personal view I really recommend this, especially on socketless connections like this one, a lot of computation and calls for the length of the buffer. Itβs not easy to debug sometimes if you are not fully aware of what you are doing.
Note 1 Be careful with non - zeros in the buffer when you are waiting for the server to move / position or whatever if you plan to use the 1st method.
Note 2 You can just send an integer or float , convert it and versa without having to cut or multiply .
Let new game network developers find this answer useful, since we cannot send or receive except char*
with UDP sendto (), recvfrom ().