Skip to content

Instantly share code, notes, and snippets.

@rodrigopmatias
Last active December 22, 2015 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigopmatias/6417147 to your computer and use it in GitHub Desktop.
Save rodrigopmatias/6417147 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#ifndef byte
typedef char byte;
#endif
/**
* Converte uma varivavel float para Bytes
* @param number Numero para ser convertido para bytes
* @return Ponteiro para região de memória do typo bytes
**/
byte * FloatToByte(float number);
/**
* Converte de bytes para float
* @params slot Posição de memoria apontada por variável do tipo byte
* @return Retorna um float
**/
float ByteToFloat(byte * slot);
int main(int argc, char ** argv) {
float num;
byte * slot;
num = 123456.78;
//Aloca o ponteiro de bytes com o tamanho de um float
slot = FloatToByte(num);
printf("%12.2f -> %s\n", num, slot);
num = 0.0;
printf("%12.2f\n", num);
//Copia o valor binario para dentro do float
num = ByteToFloat(slot);
printf("%12.2f\n", num);
free(slot);
return 0;
}
byte * FloatToByte(float number) {
byte * slot;
slot = (byte *)malloc(sizeof(float));
memcpy((void *)slot, (void *)(&number), sizeof(float));
return slot;
}
float ByteToFloat(byte * slot) {
float number;
memcpy((void *)(&number), (void *)slot, sizeof(float));
return number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment