4-byte char from hex to float

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MrL0co
    New Member
    • Jan 2010
    • 2

    4-byte char from hex to float

    he there,
    I am trying to read out a .md3 file.
    i am stuck on a point where i have to convert a 8-bit hexedecimal char to a float.
    and change it from little endian to big endian

    this is how far i got

    Code:
    	unsigned char tmp[4];
    	f32 test;
    
    	fread(&tmp, 1, 4, f);
    	test = bitshiftf32(tmp);
    
    f32 bitshiftf32(unsigned char val[4]) {
    	return val[0]|(val[1]<<8)|(val[2]<<16)|(val[3]<<24);
    	}
    f being the file it readss out
    test being the end result
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    As c/c++ standart doesn't mandate use of IEEE-754 32-bit floating-point for 'float' you probably have to convert it by yourself - get mantissa, add missing '1' bit, multiply 2 to the power of exponent.
    Or, assuming that float is IEEE-754 32 bit, just
    unsigned char val[4];
    float x = *(float*)val;

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Does the MD3 specification tell you how to interpret the 4-byte floating-point value? If so, then you should write code that explicitly decodes it accordingly; rather than casting the byte array into a native type. The casting trick might work for you, but it is brittle -- it might stop working when you upgrade to the next version of your compiler.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Code:
        f32 bitshiftf32(unsigned char val[4]) { 
            return val[0]|(val[1]<<8)|(val[2]<<16)|(val[3]<<24); 
            }
        val is an unsigned char. Probably 8 bits. So you can shift it left up to 7 places. What does shifting it left 16 or 24 do?

        Comment

        • MrL0co
          New Member
          • Jan 2010
          • 2

          #5
          tnx newb16 that works

          Comment

          Working...