C Bit Manipulation Help

Sep 22, 2016 at 3:26am
Hey everyone. I'm having trouble with this homework assignment and I would really appreciate some help/hints to get me started. I've basically been given a template and I have to fill in the functions. I'm only allowed to use &, |, ^, ~, !, >>, and << operators to complete this assignment. For example, the code below is one of the functions I need to fill in. For this specific one, I need to determine if the two ints are equal and return 'true'.
1
2
3
4
bool isEqual(int a, int b){
  
  return true;
}

Let's say both a and b are equal to 7. How could I do this using only the operators listed above?
Another, slightly more difficult function I've been given is:
1
2
3
4
unsigned short flipEndian(unsigned short a){
  
  return 0;
}

For the code above, I need to return a new short with flipped bits.

I hope I'm making sense! And I really appreciate any responses!
Sep 22, 2016 at 3:46am
The isEqual() requires you to think about the bitwise operations (AND, OR, and XOR). One of those should allow you to combine the operands to get a unique result. (hint!)

The flipEndian() function requires the use of <<, >>, and &, and will require a loop. The only thing is that you will have to assume a number of bits in a short: use 16. You'll need your input (argument) and an output (initialize with zero).

Hope this helps.
Sep 22, 2016 at 8:24am
Hi,

To do the job, you need to figure out what is an int.

7 is 0000 0111 (lets say int is 2 bytes)

Now what using XOR :

0000 0111 XOR 0000 0111 is 0000 0000 (hint for function 1)

and

0000 0111 XOR 1111 1111 is 1111 1000 ((hint for function 2)

hope that helps

Sep 22, 2016 at 8:56am
What does "flipEndian" mean?
I have never heard of such a concept.
Sep 22, 2016 at 11:37am
Topic archived. No new replies allowed.