Home > Net >  Float to Binary in C
Float to Binary in C

Time:04-09

I am asked to convert a float number into a 32 bit unsigned integer. I then have to check if all the bits are zero but I am having trouble with this. Sorry I am new to C

This is what I am doing

float number = 12.5;
// copying number into a 32-bit unsigned int
unsigned int val_number = *((unsigned int*) &number);

At this point I'm very confused on how to check if all bits are zero.

I think I need to loop through all the bits but I don't know how to do that.

CodePudding user response:

To copy the bytes of a 32-bit float to an integer, best to copy to an integer type that is certainly 32-bit. unsigned may be less, same or more than 32-bits.

#include <inttypes.h>

float number = 12.5;
uint32_t val_number32;  // 32-bit type
memcpy(&val_number32, &number, sizeof val_number32);

Avoid the cast and assign. It leads to aliasing problems with modern compilers @Andrew.

"... need cast the addresses of a and b to type (unsigned int *) and then dereference the addresses" reflects a risky programing technique.


To test if the bits of the unsigned integer are all zero, simply test with the constant 0.

int bit_all_zero = (val_number32 == 0);

An alternative is to use a union to access the bytes from 2 different encodings.

union {
  float val_f;
  uint32_t val_u;
} x = { .val_f = 12.5f };
int bit_all_zero = (x.val_u == 0);

CodePudding user response:

Checking if all the bits are zero is equivalent to checking if the number is zero.

So it would be int is_zero = (val_number == 0);

  •  Tags:  
  • c
  • Related