Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations and shifts

Im having some trouble understanding how and why this code works the way it does. My partner in this assignment finished this part and I cant get ahold of him to find out how and why this works. I've tried a few different things to understand it, but any help would be much appreciated. This code is using 2's complement and a 32-bit representation.

/* 
 * fitsBits - return 1 if x can be represented as an 
 *  n-bit, two's complement integer.
 *   1 <= n <= 32
 *   Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int fitsBits(int x, int n) {
    int r, c;
    c = 33 + ~n;
    r = !(((x << c)>>c)^x);
    return r;
}
like image 903
Scalahansolo Avatar asked Feb 09 '13 22:02

Scalahansolo


People also ask

What are bitwise shift operators?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

How do bitwise shifts work?

The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue.

How do you calculate bitwise Shift?

To calculate a left shift by 3 bits, follow these steps: Get your number in a binary format, e.g., 0000 0101 . Shift your bit string 3 positions to the left, discarding the digits falling out of scope, and filling up from the right with 0's: 0010 1000 . And that's it; you performed a shift of 3 bits to the left.

What are shift operations in C?

It is a binary operator that requires two operands to shift or move the position of the bits to the left side and add zeroes to the empty space created at the right side after shifting the bits.


1 Answers

c = 33 + ~n;

This calculates how many high order bits are remaining after using n low order bits.

((x << c)>>c

This fills the high order bits with the same value as the sign bit of x.

!(blah ^ x)

This is equivalent to

blah == x
like image 61
Code-Apprentice Avatar answered Sep 19 '22 19:09

Code-Apprentice