Skip to content

Instantly share code, notes, and snippets.

@Charl13
Last active August 31, 2021 06:52
Show Gist options
  • Save Charl13/c61fe2f5ee6793aff63068b0d49d689d to your computer and use it in GitHub Desktop.
Save Charl13/c61fe2f5ee6793aff63068b0d49d689d to your computer and use it in GitHub Desktop.
Convert float to 16-bit integer to bytes
#include <stdio.h>
#include <stdint.h>
/**
* Output result:
*
* Float: -172.500000
* Integer (16 bit): -172
* Bytes (as decimal): 84, -1
* Result (integer 16-bit): -172
*/
int main() {
float source = -172.5;
printf("Float: %f\n", source);
int16_t sourceInteger = static_cast<int16_t>(source);
printf("Integer (16 bit): %d\n", sourceInteger);
char *sourceBytes = static_cast<char*>(
static_cast<void*>(&sourceInteger));
printf(
"Bytes (as decimal): %d, %d \n",
sourceBytes[0],
sourceBytes[1]);
int16_t destinationInteger;
char *destinationBytes = static_cast<char*>(
static_cast<void*>(&destinationInteger));
destinationBytes[0] = sourceBytes[0];
destinationBytes[1] = sourceBytes[1];
printf("Result (integer 16-bit): %d", destinationInteger);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment