Ahmed Saleh Ahmed Saleh - 9 days ago 5x
C Question

Convert Float to hex

I would like to convert float value to hex without using printf, or scanf, I'm doing it in embedded system that doesn't have any standard library like printf or sprintf.
The float can be negative, and can be fractional.

using the code from the answer, I'm getting 1B41

float temp = 27.25;
char byte[3];
unsigned char * ptr = (unsigned char *)&temp;

for (i=0; i<sizeof(float); i++) {

cvt_hex(ptr[i], byte);
b[p++] = byte[0];
b[p++] = byte[1];
b[p++] = byte[2];


At least as I read your comments, what you want is to just display a hex representation of the bytes that make up the float in question.

In that case, it's probably easiest to just do something on this general order:

void cvt_hex(unsigned char byte, char *result) { 
    static char hex[] = "0123456789ABCDEF";

    result[0] = hex[byte >> 4];
    result[1] = hex[byte & 0xf];
    result[2] = '\0';

void show_hex(float in) { 
    unsigned char *ptr = (unsigned char *)&in;

    for (i=0; i<sizeof(float); i++) {
        char byte[3];
        cvt_hex(ptr[i], byte);

You haven't really told us enough to guess how to implement show, but it's assumed to take some string of bytes, and display them appropriately.