473,698 Members | 2,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bit representation of a float

In an effort to write a simple rounding function, I wrote the following code
out of
curiosity. My question is, can I rely on the output to 'make sense'? As an
added
'exercise' I tried to write the code in a portable manner, not just for my
box that
uses 8-bit bytes and 4-byte floats.

Comments and critiques are welcome. Thanks.

/* display the binary representation of a float variable */
#include <stdio.h>
#include <limits.h>

int main(void) {
int i, j;
float f, *pf;
char *pc;

f = 42; /* assign some arbitrary value */
pf = &f;
pc = (char *)pf;

for (i = 0; i < sizeof(float); i++) {
for (j = 0; j < CHAR_BIT; j++) {
printf("%d", *pc & (1 << j) ? 1 : 0);
fflush(stdout);
}
pc++;
printf(" ");
fflush(stdout);
}

return 0;
}

--
Gary Baydo
email: my initial and last name at mindspring.com
Anyone can make mistakes, but only an idiot persists in his error.
- Cicero
Aug 15 '07 #1
7 8378
Gary Baydo <gb****@mindspr ing.comwrote:
In an effort to write a simple rounding function, I wrote the following code
out of curiosity. My question is, can I rely on the output to 'make sense'?
As an added 'exercise' I tried to write the code in a portable manner, not
just for my box that uses 8-bit bytes and 4-byte floats.
Comments and critiques are welcome. Thanks.
/* display the binary representation of a float variable */
#include <stdio.h>
#include <limits.h>
int main(void) {
int i, j;
float f, *pf;
char *pc;
f = 42; /* assign some arbitrary value */
pf = &f;
pc = (char *)pf;
for (i = 0; i < sizeof(float); i++) {
for (j = 0; j < CHAR_BIT; j++) {
printf("%d", *pc & (1 << j) ? 1 : 0);
fflush(stdout);
}
pc++;
printf(" ");
fflush(stdout);
}
return 0;
}
Looks ok to me. Just that always flushing stdout seems a bit
superfluous and if you want to output just a singe char using
printf() is a bit of overkill. If you want to tighten it a bit
(and you don't mind that f's value gets changed in the process)
you could try:

#include <stdio.h>
#include <limits.h>

int main( void ) {
size_t i, j;
float f = 42;
unsigned char *pc = ( unsigned char * ) &f;

for ( i = 0; i < sizeof f; pc++, i++ ) {
for ( j = 0; j < CHAR_BIT; *pc >>= 1, j++ )
putchar( ( *pc & 1 ) + '0' );
putchar( ' ' );
}

putchar( '\n' );
return 0;
}
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Aug 15 '07 #2
Jens Thoms Toerring said:

<snip>
If you want to tighten it a bit
(and you don't mind that f's value gets changed in the process)
you could try:

#include <stdio.h>
#include <limits.h>

int main( void ) {
size_t i, j;
float f = 42;
unsigned char *pc = ( unsigned char * ) &f;

for ( i = 0; i < sizeof f; pc++, i++ ) {
for ( j = 0; j < CHAR_BIT; *pc >>= 1, j++ )
putchar( ( *pc & 1 ) + '0' );
Won't this put the bits the wrong way round?

I suggest this instead:

#include <stdio.h>
#include <limits.h>

void fprintbyte(FILE *fp, unsigned char n, int bits)
{
if(bits 1)
{
fprintbyte(fp, n / 2, bits - 1);
}
putc((n & 1) + '0', fp);
}

void fprintbin(FILE *fp, void *vp, size_t len)
{
unsigned char *p = vp;
while(len-- 0)
{
fprintbyte(fp, *p++, CHAR_BIT);
}
putchar('\n'); /* clearly optional - adjust to taste */
}

int main(void)
{
long double ld = 42.0L;
double d = 42.0;
float f = 42.0F;
fprintbin(stdou t, &ld, sizeof ld);
fprintbin(stdou t, &d, sizeof d);
fprintbin(stdou t, &f, sizeof f);
return 0;
}

On my system, the output is as follows:

000000000000000 000000000000000 000000000000000 000000000001010 100000000100010 000000000000001 000000
000000000000000 000000000000000 000000000000000 000010001010100 0000
000000000000000 000101000010000 10

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 15 '07 #3
"Gary Baydo" <gb****@mindspr ing.comwrote:
In an effort to write a simple rounding function, I wrote the following code
out of curiosity. My question is, can I rely on the output to 'make sense'?
Yes and no. See below.
As an added 'exercise' I tried to write the code in a portable manner, not
just for my box that uses 8-bit bytes and 4-byte floats.

Comments and critiques are welcome. Thanks.

/* display the binary representation of a float variable */
#include <stdio.h>
#include <limits.h>

int main(void) {
int i, j;
float f, *pf;
char *pc;
This should really be an unsigned char *.
f = 42; /* assign some arbitrary value */
pf = &f;
pc = (char *)pf;
You don't need this double assignment; directly writing

pc = (unsigned char *)&f;

works just as well.
for (i = 0; i < sizeof(float); i++) {
for (j = 0; j < CHAR_BIT; j++) {
printf("%d", *pc & (1 << j) ? 1 : 0);
fflush(stdout);
}
pc++;
printf(" ");
fflush(stdout);
}
You really do not need to fflush(stdout) after every single character.
Doing it at the end of the entire loop should work just fine.

You can rely on the output making _some_ sense, since the representation
of floating point numbers must follow certain patterns as laid out in
the Standard. You must have a fixed base and precision for each floating
point type, and each FPN must have a sign, an exponent, and a fixed
number of significand digits. However, how these numbers are represented
in the underlying bits is not specified by the Standard, so you may not
immediately recognise the pattern; but it must be there. (Most likely,
probably, you will see IEC 60559 numbers. But that's not required.)

Richard
Aug 15 '07 #4
Richard Heathfield <rj*@see.sig.in validwrote:
Jens Thoms Toerring said:
<snip>
If you want to tighten it a bit
(and you don't mind that f's value gets changed in the process)
you could try:

#include <stdio.h>
#include <limits.h>

int main( void ) {
size_t i, j;
float f = 42;
unsigned char *pc = ( unsigned char * ) &f;

for ( i = 0; i < sizeof f; pc++, i++ ) {
for ( j = 0; j < CHAR_BIT; *pc >>= 1, j++ )
putchar( ( *pc & 1 ) + '0' );
Won't this put the bits the wrong way round?
Well, that seemed to be the way the OP wanted it, least significant
byte first and also least significant bit of each byte first.
I suggest this instead:
#include <stdio.h>
#include <limits.h>
void fprintbyte(FILE *fp, unsigned char n, int bits)
{
if(bits 1)
{
fprintbyte(fp, n / 2, bits - 1);
}
putc((n & 1) + '0', fp);
}
Recursion is fun but I probably wouldn't have used it in this
situation;-)
Regards; Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Aug 15 '07 #5
In article <46************ *****@news.xs4a ll.nl>,
Richard Bos <rl*@hoekstra-uitgeverij.nlwr ote:
>You can rely on the output making _some_ sense, since the representation
of floating point numbers must follow certain patterns as laid out in
the Standard. You must have a fixed base and precision for each floating
point type, and each FPN must have a sign, an exponent, and a fixed
number of significand digits. However, how these numbers are represented
in the underlying bits is not specified by the Standard, so you may not
immediately recognise the pattern; but it must be there.

I have just reviewed the C89 wording on it, and I'm not -convinced-
that the precision must be fixed.

FLT_RADIX must be a constant. Everything else in <float.his
allowed to be non-constant expressions ("non-constant" is specifically
mentioned.)

FLT_MANT_DIG and kin are defined in C89 as

number of decimal digits, q, such that any floating point number
with q decimal digits can be rounded into a floating-point
number with p radix b digits and back again without change
to the q decimal digits

It seems to me that if you had some kind of variable precision, then
FLT_MANT_DIG and kin could be the worst-case numbers, with the
possibility that you might get noticably more accuracy on some values.

The whole s/b/e/p/f[k] floating point model is just that, a -model-,
an abstraction, that need not necessarily be followed internally as long
as you can get the necessary behaviours to work out.
Not that I can see any good reason to implement anything else -- not even
any half-baked reason. But if someone implemented a format that (say)
had variable amounts of significant storage and padded the rest
[e.g., some kind of toaster where 1/32 was the finest resolution needed
for 99% of the calculations], then I don't know that that'd be ruled out.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Aug 15 '07 #6
Gary Baydo wrote:
>
In an effort to write a simple rounding function, I wrote the following code
out of
curiosity. My question is, can I rely on the output to 'make sense'? As an
added
'exercise' I tried to write the code in a portable manner, not just for my
box that
uses 8-bit bytes and 4-byte floats.

Comments and critiques are welcome. Thanks.

/* display the binary representation of a float variable */
#include <stdio.h>
#include <limits.h>

int main(void) {
int i, j;
float f, *pf;
char *pc;

f = 42; /* assign some arbitrary value */
pf = &f;
pc = (char *)pf;

for (i = 0; i < sizeof(float); i++) {
for (j = 0; j < CHAR_BIT; j++) {
printf("%d", *pc & (1 << j) ? 1 : 0);
fflush(stdout);
}
pc++;
printf(" ");
fflush(stdout);
}

return 0;
}
I wrote a function named bitstr, for that purpose.
bitstr works with any type, not just floats.

Here's what the output looks like on my machine:

/* BEGIN output from bitstr.c */

0.333333 = 001111101010101 010101010101010 11
0.666667 = 001111110010101 010101010101010 11
1.333333 = 001111111010101 010101010101010 11
2.666667 = 010000000010101 010101010101010 11
5.333333 = 010000001010101 010101010101010 11
10.666667 = 010000010010101 010101010101010 11
21.333334 = 010000011010101 010101010101010 11
42.666668 = 010000100010101 010101010101010 11

/* END output from bitstr.c */
/* BEGIN bitstr.c */

#include <limits.h>
#include <stdio.h>

#define STRING "%15f = %s\n"
#define E_TYPE float
#define INITIAL (1.0f / 3)
#define FINAL 50
#define INC(E) ((E) *= 2)

typedef E_TYPE e_type;

void bitstr(char *str, const void *obj, size_t n);

int main(void)
{
e_type e;
char ebits[CHAR_BIT * sizeof e + 1];

puts("\n/* BEGIN output from bitstr.c */\n");
for (e = INITIAL; FINAL >= e; INC(e)) {
bitstr(ebits, &e, sizeof e);
printf(STRING, e, ebits);
}
puts("\n/* END output from bitstr.c */");
return 0;
}

void bitstr(char *str, const void *obj, size_t n)
{
unsigned mask;
const unsigned char *byte = obj;

while (n-- != 0) {
mask = ((unsigned char)-1 >1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask != 0);
}
*str = '\0';
}

/* END bitstr.c */
--
pete
Aug 15 '07 #7
On 2007-08-15 12:58, Richard Heathfield <rj*@see.sig.in validwrote:
Jens Thoms Toerring said:
>int main( void ) {
size_t i, j;
float f = 42;
unsigned char *pc = ( unsigned char * ) &f;

for ( i = 0; i < sizeof f; pc++, i++ ) {
for ( j = 0; j < CHAR_BIT; *pc >>= 1, j++ )
putchar( ( *pc & 1 ) + '0' );

Won't this put the bits the wrong way round?
On a little-endian system, it's consistent.

I suggest this instead:

#include <stdio.h>
#include <limits.h>

void fprintbyte(FILE *fp, unsigned char n, int bits)
{
if(bits 1)
{
fprintbyte(fp, n / 2, bits - 1);
}
putc((n & 1) + '0', fp);
}

void fprintbin(FILE *fp, void *vp, size_t len)
{
unsigned char *p = vp;
while(len-- 0)
{
fprintbyte(fp, *p++, CHAR_BIT);
}
putchar('\n'); /* clearly optional - adjust to taste */
}
This is consistent on a big-endian system. But on a little-endian system
(like yours) the output is inconsistent: Bytes are output least
significant first, but bits within the bytes are output most significant
first, which means that adjacent bits in memory aren't adjacent in the
output:
On my system, the output is as follows:

000000000000000 000000000000000 000000000000000 000010001010100 0000
| . | . | . | . | . | . EEEE. SEEEEEEE
0000 1000000
3210 0987654

I've marked the sign bit and the the exponent here. You notice that
the sign bit appears to be in middle of the bitstring and the exponent
bits 3 and 4 don't appear to be adjacent. This is hard to read.

Here is my version (which does a bit more than just print bits):

static void printdouble(dou ble f) {
union {
doubleint i;
double f;
} u;
doubleint e;
doubleint m;

u.f = f;

printf(doublefo rmat, f);
printf(": ");
printf("%c ", (u.i & SIGN_DBL) ? '-' : '+');
u.i &= ~SIGN_DBL;
e = u.i >MANT_DBL;
printbinary(e, BITS_DBL-1-MANT_DBL);

m = (u.i & (((doubleint)1 << MANT_DBL) - 1));
if (e == 0) {
printf(" [0.]");
} else {
printf(" [1.]");
}
printbinary(m, MANT_DBL);
printf("\n");
}

(doubleint is typedef'ed to unsigned long or unsigned long long
(uint64_t didn't exist in 1998) and various constants are hard-coded for
IEEE-754 numbers - the whole program is at
http://www.hjp.at/programs/ieeefloat/ if somebody's interested)

hp
--
_ | Peter J. Holzer | I know I'd be respectful of a pirate
|_|_) | Sysadmin WSR | with an emu on his shoulder.
| | | hj*@hjp.at |
__/ | http://www.hjp.at/ | -- Sam in "Freefall"
Aug 18 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2082
by: Bengt Richter | last post by:
Peculiar boundary cases: >>> 2.0**31-1.0 2147483647.0 >>> int(2147483647.0) 2147483647L >>> int(2147483647L ) 2147483647 >>> >>> -2.0**31
5
4545
by: Yodai | last post by:
Hi all! I have an int that comes with a value like 0x07fa and I have to turn it into a float value of 204.2 decimal to display it.... if I try to divide it by 10 I get bogus numbers. I presume I have to make it decimal before calculating, but I am not sure about it. Any light upon this simple (or it seems to me so, at least) begginner problem? TIA..
2
2662
by: Shi Jin | last post by:
Hi there, I have been thinking this for quite a while: if we are considering the number of different representations of one type,say int and float, is there any difference as long as they are the same bit long? I am thinking this as an example for representing different colors. Is the number of differnt colors a 32-bit integer can represent any differnt from using a 32-bit floating point? It seems to me float has much more choices...
7
3644
by: A. L. | last post by:
Consider following code segment: #1: double pi = 3.141592653589; #2: printf("%lf\n", pi); #3: printf("%1.12lf\n", pi); #4: printf("%1.15lf\n", pi); The above code outputs as following: 3.141593
10
4180
by: 63q2o4i02 | last post by:
Hi, I'm using python to run some lab equipment using PyVisa. When I read a list of values from the equipment, one of the fields is 32 bits of flags, but the value is returned as a floating point number, either in ASCII format, or pure binary. In either case, since I'm using PyVisa, it converts the number to a single precision floating point, and that's what I have to work with. The question is how do I recover the bits out of this...
15
6990
by: thomas.mertes | last post by:
For a hash function I want to reinterpret the bits of a float expression as unsigned long. The normal cast (unsigned long) float_expression truncates the float to an (unsigned long) integer. But this is not the effect I want for a hash function. With unions my hash function can be implemented:
11
6461
by: rahulsinner | last post by:
hi everyone, main() { float f=0.7; if ( f< 0.7) printf("C"); else printf("C++"); }
7
2966
by: Stein Gulbrandsen | last post by:
What is the best way to get to the integer representation of a float? I would like to do int& toIntByCast (float& a) {return *reinterpret_cast<int*(&a);} but is this legal? Is this safer? int toIntByUnion (const float& a) { union {float f; int i;} u = {a}; return u.i;
15
3763
by: khan | last post by:
Hi, I read that pointer representation can non-zero bit pattern, machine specific.Compiler when comes accross value '0' in pointer context, converts it to machine specific null pointer bit-pattern. My question is if a program refers to that specific value which is used by the machine to refer to null pointer, how compiler treats that?.
1
7991
by: krishna81m | last post by:
I am a newbie and have been trying to understand conversion from double to int and then back to int using the following code was posted on the c++ google group. Could someone help me out with understanding why and how a double can be represented in bits and bytes and which of the following can allow us to view the binary representation, unsigned char representation and then convert back to int please... #include<iostream> #include<iomanip>...
0
8603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9026
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8893
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2328
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.