Reputation: 5797
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?
Upvotes: 1
Views: 1897
Reputation: 19304
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.
Upvotes: 3
Reputation: 387
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?
Upvotes: 1
Reputation: 44288
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.
Upvotes: 1