views:

111

answers:

3

Hey everybody. I am learning bit wise operation and arithmetic operations in C but I am a bit confused about some of it. I am working through some of the review questions in my book but the book only has answers for the odd number questions so I would like to pose some questions for you guys so I can tell if I am on the right track. Thanks a whole lot.

Each of these can be written with a straight-line code (loops and conditionals are not necessary) Example of one I have done:

// this returns 0 if x==y and 1 otherwise
Int isNotEqual (int x, int y) {
return !(x ^ y)
}

My questions to you: How would you....

  • Return count of number of 1s in word using any of the following operations: ! ~ & ^ | + << >>

  • Compute !x without using ! Using any of the following operations: ! ~ & ^ | + << >>

  • Return a mask that marks the position of the least significant 1 bit using any of the following operations: ! ~ & ^ | + << >>

  • Absolute value of x using any of the following operations: ! ~ & ^ | + << >>

  • Determine if you can compute x + y without overflow using any of the following operations: ! ~ & ^ | + << >>

Any help is greatly appreciated. Thank you so much!

+2  A: 

This page can lead you to all the answers.

Donotalo
+2  A: 

Some hints:

0xFF (hex) = 256 - 1 = 255 (dec) = 11111111 (bin)    
0xAABBCCDD & 0x00FF0000 == 0x00BB0000    
1 << n == 2^n    
x << n = x * 2^n    
x >> n = x / 2^n    
x & 0x000000FF = x % 2^8    
x is positive if its most significant bit (x & (1 << 31)) is not 0

For more details I can only suggest you to read this book: http://www.hackersdelight.org/ Explaining a dosen examples is too much, I think.

Andrey Breslav
+2  A: 

Here's the definitive page on bit-twiddling. Study the examples and figure out why they work, and then figure those questions out yourself.

zildjohn01