Skip to content

Instantly share code, notes, and snippets.

@bgstaal
Created May 28, 2013 18:37
Show Gist options
  • Save bgstaal/5665027 to your computer and use it in GitHub Desktop.
Save bgstaal/5665027 to your computer and use it in GitHub Desktop.
Float to buffer to string back to float
float f = -0.123456;
size_t n = sizeof(f); //number of bytes in a float
unsigned char buffer[n]; //create buffer of n bytes
memcpy(&buffer, &f, n); // copy underlying bytes from float to buffer
string str((char *)buffer, n); //instantiate new string with contents of buffer
float f2;
memcpy(&f2, str.data(), n); //copy bytes from string data prop to f2
printf("%f\n", f2); // prints -0.123456
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment