Skip to content

Instantly share code, notes, and snippets.

@khajavi
Created May 29, 2013 04:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save khajavi/5667960 to your computer and use it in GitHub Desktop.
Save khajavi/5667960 to your computer and use it in GitHub Desktop.
Converting floating-point number to IEEE754 representation by using union and struct in c.
#include <stdio.h>
/*
* See also : http://class.ece.iastate.edu/arun/CprE281_F05/ieee754/ie5.html
*/
union FloatingPointIEEE754 {
struct {
unsigned int mantissa : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
} raw;
float f;
} number;
int main() {
number.f = -6.8;
printf("%x, %x, %x", number.raw.mantissa, number.raw.exponent, number.raw.sign );
return 0;
}
@luisfergromo
Copy link

i have a question, ¿How to 64 bits?
Its ok:
struct { unsigned long long mantissa : 52; unsigned short int exponent : 11; unsigned int sign : 1; }doublePrecision;

@kamalhyder
Copy link

Can i do the bitwise operation on these unsignes integers now?

I have to vanish some bits of mantissa... How can i do this?

@mebeim
Copy link

mebeim commented Feb 14, 2018

Not pretty, but I came up with this one to properly display the number. @kamalhyder

#include <stdio.h>

#define BYNARY_FMT "%u%u%u%u%u%u%u%u"
#define BYTE_TO_BIN(b) ((b) & 0x80 ? 1 : 0),\
                       ((b) & 0x40 ? 1 : 0),\
                       ((b) & 0x20 ? 1 : 0),\
                       ((b) & 0x10 ? 1 : 0),\
                       ((b) & 0x08 ? 1 : 0),\
                       ((b) & 0x04 ? 1 : 0),\
                       ((b) & 0x02 ? 1 : 0),\
                       ((b) & 0x01 ? 1 : 0)
					   
#define BIT_FMT "%u"
#define NTH_BIT(b, n) ((b) & (1 << n) ? 1 : 0)

union FloatingPointIEEE754 {
	struct {
		unsigned int m: 23;
		unsigned int e: 8;
		unsigned int s: 1;
	} raw;
	float f;
} ieee754;

int main() {
	ieee754.f = -6.8;
		
	printf(
		BIT_FMT " "
		BYNARY_FMT " "
		BIT_FMT BIT_FMT BIT_FMT BIT_FMT BIT_FMT BIT_FMT BIT_FMT BYNARY_FMT BYNARY_FMT "\n\n",
		
		// SIGN
		NTH_BIT    (ieee754.raw.s      , 0),
		
		// EXPONENT
		BYTE_TO_BIN(ieee754.raw.e         ),
		
		// MANTISSA
		NTH_BIT    (ieee754.raw.m >> 16, 6),
		NTH_BIT    (ieee754.raw.m >> 16, 5),
		NTH_BIT    (ieee754.raw.m >> 16, 4),
		NTH_BIT    (ieee754.raw.m >> 16, 3),
		NTH_BIT    (ieee754.raw.m >> 16, 2),
		NTH_BIT    (ieee754.raw.m >> 16, 1),
		NTH_BIT    (ieee754.raw.m >> 16, 0),
		BYTE_TO_BIN(ieee754.raw.m >> 8    ),
		BYTE_TO_BIN(ieee754.raw.m         )
	);
	
	return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment