Floating point Hex.

This is a discussion on Floating point Hex. within the C Programming forums, part of the General Programming Boards category; I need to print a floating point number in hex using the IEE standards for a double. I tried this ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    3

    Floating point Hex.

    I need to print a floating point number in hex using the IEE standards for a double.

    I tried this but it didn't work:
    Code:
    double dNum=5.5;
    printf("%X", dNum);
    I also tried:
    Code:
    double dNum=5.5;
    printf("%X", (int)dNum);
    The second one just printed out the hex for an integer. I looked at the dNum in memory with the debuger and that is what I want. Is there anyway to just copy the exact hex number from memory without converting it back to decimal?

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Is this what you want?
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
    	int    i;
    	double d = 5.5;
    	unsigned char d_bytes[sizeof(d)];
    
    	memcpy(d_bytes, &d, sizeof(d));
    
    	for (i = 0; i < sizeof(d); i++)
    	{
    		printf("%02X", d_bytes[i]);
    	}
    
    	getchar();
    }

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    3
    It didn't work.
    The result is supposed to be: 40B00000.

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    3
    You had it backwords.

    it goes like this:
    Code:
    for (i = sizeof(d)-1; i > 0; i--)
    {
    	printf("%02X", d_bytes[i]);
    }
    and the result is supposed to be: 4016000000000000 not 40B00000. It works now. Thanks for the help.

  5. #5
    Registered User fischerandom's Avatar
    Join Date
    Aug 2005
    Location
    Stockholm
    Posts
    71

    Using a union

    Code:
    int		main( ) {
    	#define FP_SZ	8
    	
    	union {
    		double			fp;
    		unsigned char	byte[ FP_SZ ];
    	} x;
    	
    	int		i;
    	
    	x.fp = ( double ) 5.5;
    	
    	printf( "Floating Point: %f\n", x.fp );
    	printf( "Hex: " );
    	
    	for ( i = 0; i < FP_SZ; ++i )
    		printf( "%02X ", x.byte[ i ] );
    	
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  2. floating point binary program, need help
    By ph34r me in forum C Programming
    Replies: 4
    Last Post: 11-10-2004, 06:10 AM
  3. floating point question
    By Eric Cheong in forum C Programming
    Replies: 8
    Last Post: 09-10-2004, 10:48 PM
  4. 2 questions about floating point and %
    By ams80 in forum C Programming
    Replies: 2
    Last Post: 08-14-2002, 10:55 AM
  5. Replies: 2
    Last Post: 09-10-2001, 12:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21