Created
December 21, 2020 09:54
-
-
Save ericherman/6ae3d38b694d0eacaa947f6586b819b6 to your computer and use it in GitHub Desktop.
simple float persistance to byte device
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* float-transmission.c: simple float persistance to byte device */ | |
/* Copyright 2020 (C) Eric Herman */ | |
/* License: WTFPL – Do What the Fuck You Want to Public License */ | |
/* http://www.wtfpl.net */ | |
/* | |
$ gcc -Wall -Wextra -o ./float-transmission ./float-transmission.c | |
$ ./float-transmission | |
sizeof(float) == 4 | |
original == 0.666667 | |
bytes == 0xabaa2a3f | |
round_trip == 0.666667 | |
do they match? yes | |
*/ | |
/* there are byte order issues to consider if going between machines of | |
* different endian-ness, but not needed in our simple persistance case */ | |
#include <stddef.h> | |
/* this is intentially verbose to make a clear example do it in fewer | |
* lines in your own firmware */ | |
void bytes_from_float(unsigned char *bytes, float f) | |
{ | |
float *fptr = NULL; | |
unsigned char *fbytes = NULL; | |
fptr = &f; | |
fbytes = (unsigned char *)fptr; | |
for (size_t i = 0; i < sizeof(float); ++i) { | |
bytes[i] = fbytes[i]; | |
} | |
} | |
float float_from_bytes(unsigned char *bytes) | |
{ | |
float *fbytes = NULL; | |
float f = 0.0; | |
fbytes = (float *)bytes; | |
f = *fbytes; | |
return f; | |
} | |
#include <stdio.h> | |
int main(void) | |
{ | |
unsigned char float_byte_buffer[sizeof(float)]; | |
float original = 2.0 / 3.0; | |
float round_trip = 0.0; | |
printf("sizeof(float) == %zu\n", sizeof(float)); | |
printf("original == %g\n", original); | |
bytes_from_float(float_byte_buffer, original); | |
printf("bytes == 0x"); | |
for (size_t i = 0; i < sizeof(float); ++i) { | |
printf("%02x", float_byte_buffer[i]); | |
} | |
printf("\n"); | |
round_trip = float_from_bytes(float_byte_buffer); | |
printf("round_trip == %g\n", round_trip); | |
int error = (original != round_trip); | |
printf("do they match? %s\n", error ? "no" : "yes"); | |
return error; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment