1

Given a two floating point Numbers A and B, which are command line arguments, I must create methods to do bitwise operations on them. Including And, Or, Not, xOr, floating Point addition etc...

How can I access each bit in C? I need to access the specific 1's and 0's. Any idea how?

Snow_Mac
  • 5,727
  • 17
  • 54
  • 80
  • Looks like a duplicate of [this](http://stackoverflow.com/questions/1723575/how-to-perform-a-bitwise-operation-on-floating-point-numbers) – Matt Phillips Feb 22 '12 at 19:40
  • related: http://stackoverflow.com/questions/1723575/how-to-perform-a-bitwise-operation-on-floating-point-numbers (about C++, but the answers apply to C). – Wooble Feb 22 '12 at 19:40

3 Answers3

3

Here's an example using unions, as Keith suggests.


/* -std=c99 */
#include <stdio.h>

int main(int argc, char * argv[]) {

  /* note, I'm assuming an int has the same size of a float here */
  assert( sizeof(unsigned int) == sizeof(float) );

  union {
    float floating;
    unsigned int integer;
  } a;

  a.floating = 3.14;

  /* prints the bits in reverse order */
  unsigned int temp = a.integer;
  for( int i = 0; i < sizeof(float)*8; i++ ) {
    printf("%d", temp & 0x1);
    temp = temp >> 1;
  }
}

EDIT: changed signed ints to unsigned.

Tom
  • 18,685
  • 15
  • 71
  • 81
  • only thing I like when dealing with "bits" is that I'd go for unsigned int to play with. – Keith Nicholas Feb 22 '12 at 21:18
  • @Keith Nicholas you're right; unsigned ints are more intuitive. I updated my answer. (Practically-speaking, there's no difference.) – Tom Feb 22 '12 at 21:48
1

by using a union.... you can either get to each part as per :-

What's the correct way of using bitfields in C?

or simply union the whole thing to an unsigned long and then manipulate that.

Community
  • 1
  • 1
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

You have to decide what a bitwise operation on a floating point number should do first, because you can not do bitwise operations on floating point numbers.

If you cast you floating point number to an unsigned type, or separate, the sign, exponent and mantissa into three individual unsigned variables, what should the result of a bit shift be for example?

foo
  • 387
  • 2
  • 9