Last active
August 31, 2021 06:52
-
-
Save Charl13/c61fe2f5ee6793aff63068b0d49d689d to your computer and use it in GitHub Desktop.
Convert float to 16-bit integer to bytes
This file contains hidden or 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
#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