Thread: How to convert hexadecimal into floating point?

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    4

    Question How to convert hexadecimal into floating point?

    I'm trying to convert 4 hex register into floating point value using IEEE 754 floating point format.
    My device will reply 4 register value.
    The problem is that it always reply for example 0x10 as 10 when i use getc() hence using char variable to store it is not ideal.


    Code:
    union {
        char c[4];
        float f;
    } conv;

    Any solution for this problem?

  2. #2
    Registered User
    Join Date
    Jan 2013
    Posts
    106
    This is something I've had for a while that converts a float to four bytes.
    It might help
    Code:
    void float_to_bytes() {
    			unsigned char *pbyte = (unsigned char *) &aFloat;
    			for (findx=0; findx<sizeof(float); findx++) {
    			bytes[findx] = *pbyte;
    			pbyte++;
    			} // findx
    			sbuffer[floatindex] = bytes[0]; floatindex++;
    			sbuffer[floatindex] = bytes[1]; floatindex++;
    			sbuffer[floatindex] = bytes[2]; floatindex++;
    			sbuffer[floatindex] = bytes[3]; floatindex++;
    }
    

  3. #3
    Registered User
    Join Date
    Jan 2013
    Posts
    106
    I have the reverse as well,
    Here ya go:
    Code:
    float Float(charunsigned *const p) {        // convert four bytes to float
                float val;
                memcpy(&val,p,sizeof val);
                return val;
    }
    You can call it like this:
    Code:
    Float(bytes);
    
    Where bytes is the same 4 byte array as the first example.
    Last edited by xArt; 03-10-2013 at 09:35 PM.

  4. #4
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    I'm still an amateur in C language, show me an example for your second code?
    For example, my device will reply 4 different hex register
    43, 70, 80, 00. The conversion output will be 240.5.
    Last edited by zenniz; 03-11-2013 at 12:17 AM.

  5. #5
    Registered User
    Join Date
    Jan 2013
    Posts
    106
    The order of the bytes depends on the platform you're using,
    but:

    Code:
    float number;
    char bytes[4];
    
    bytes[0] = 0x43;
    bytes[1] = 0x70;
    bytes[2] = 0x80;
    bytes[3] = 0x00;
    
    
    number = Float(bytes);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to convert floating point data type
    By adityaismagic in forum C Programming
    Replies: 6
    Last Post: 10-02-2012, 03:27 PM
  2. how to convert decimal to floating point number
    By -EquinoX- in forum C Programming
    Replies: 98
    Last Post: 03-04-2008, 01:25 PM
  3. convert a floating point number to string
    By heeroyung in forum C Programming
    Replies: 1
    Last Post: 10-02-2005, 01:03 AM
  4. Convert a Floating Point Number to a String
    By maththeorylvr in forum C Programming
    Replies: 1
    Last Post: 04-21-2005, 04:40 PM

Tags for this Thread