Show Floating Point Numbers in Hex and Binary   Leave a comment

// testIEEE754ShortReal.cpp : Defines the entry point for the console application.
//

#include “stdafx.h”
#include <iostream>
#include <iomanip>

using namespace std;

#define IEEE754_EXPONENT_BIAS 0x7F

typedef unsigned int __uint;
//bit fields to extract the sign, the exponent and the mantissa
typedef struct __tagIEEE754ShortReal
{
	__uint mantissa:23;
	__uint exponent:8;
	__uint sign:1;
}IEEE754ShortReal, *LPIEEE754ShortReal;

//#pragma warning(disable:4305)
float array1[] = {
					1.0f,
					0.99999999f,
					-1.0f,
					5.75f,
					3.69f,
					3.75f,
					0.2f,
					0.4f,
					-5.75f,
					7.89f,
					67.234f,
					-12.676f,
					48.123f,
					94.521f,
					4.23f,
					12.676f,
					2.0f,
					-4.0f,
					8.0f,
					16.0f,
					-32.0f,
					64.0f,
					128.0f,
					-256.0f,
					512.0f,
					1024.0f,
					-2048.0f,
					4096.0f,
					-8192.0f,
					3.1415f,
					2.1427f,
					5.3342f,
					31.0f, 
					91.0f,
					181.0f,
					271.0f,
					366.0f,
					1000000.0f,
					2000000.0f,
					9000000.0f,
				};

char* get_binary_str(const __uint val, __uint digits)
{
	if(digits==0)
		return 0;

	char* str = new char[digits + 1];
	__uint check = 1;
	__uint bit_pos = 0;
	while(digits-- > 0)
	{
		if(check & val)
			str[bit_pos] = '1';
		else
			str[bit_pos] = '0';

		check <<= 1;
		bit_pos++;
	}
	str[bit_pos] = '';
	_strrev(str);

	return str;
}
int _tmain(int argc, _TCHAR* argv[])
{
	printf("\n\nShort Real   \tsign exponent mantissa  \t\thex-value\n\n");
	for(int index=0; index < sizeof(array1)/sizeof(array1[0]); index++)
	{
		LPIEEE754ShortReal lpsp = reinterpret_cast(&array1[index]);
		char* sexp		= get_binary_str(lpsp->exponent, 8);
		char* smantissa = get_binary_str(lpsp->mantissa, 23); 
		__uint* uif = reinterpret_cast(&array1[index]);
		printf("%2.3f    \t=  %s %s %s\t0x%08X\n", array1[index], lpsp->sign ? "1" : "0", sexp, smantissa, *uif);

		delete []sexp;
		delete []smantissa;
	}
	system("pause");
	return 0;
}
Advertisements

Posted February 2, 2013 by hmarzan

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: