-1

I've converted a float into an char array that will be sent over to a server. I want to be able to convert the char array, say from buffer[10]... to buffer [20] converted back into a single float. How can i accomplish this? I only know how to convert entire buffer using atoi but since my char buffer will contain other irrelevent data how can i selecetively do this for certain part of my array?

This is how i converted my float into an char array.

  sprintf(game->buffer,"%f",game->man[playerNumber-48].x);

    //printf("%s\n", game->buffer);

    for(int i = 0; i<11;i++)
    {
        game->send_key_to_server[i+8] = game->buffer[i];
    }

    sprintf(game->buffer,"%f",game->man[playerNumber-48].y);

    for(int i = 0; i<11;i++)
    {
        game->send_key_to_server[i+19] = game->buffer[i];
    }

Basically im sending my players x and y cordinates over to the server as chars.

xxFlashxx
  • 261
  • 2
  • 13

2 Answers2

2

Reading the comments, what you probably want to do is to serialize and de-serialize the data, so that it can be sent as raw data over some form of communication media.

For that purpose, it does not make sense any sense to convert to ASCII. Instead, you'll want a raw data format, which is most compact. This is possible if both computers have the same floating point format and the same endianess. If so, you can simply do:

memcpy(buf, &my_float, sizeof(float)); // transmitter side
memcpy(&my_float, buf, sizeof(float)); // receiver side

where "buf" is whatever data buffer you use to send/receive data through.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

To convert a string to a float, atof(), or better, strtod() is sufficient.

To convert a float to a string, code needs to insure enough precision is used and a large enough buffer to save and distinguish all float - about 17 char. Best to use some exponential format like "%e" or "%a".

//                    -  dig  .     digs               e   -  expo \0
#define FLT_STR_SIZE (1 + 1 + 1 + (FLT_DECIMAL_DIG-1) + 1 + 1 + 3 + 1)
char s[FLT_STR_SIZE];
sprintf(s, "%.*e", FLT_DECIMAL_DIG-1, some_float);

Details

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256