-1

I am writing a function with parameters:

int nbit2s(long int x, long int n){

}

I am looking to take in 64 bit number x, and find if a 2 bit representation of n bit length is possible. I am however restricted to using only bitwise operators and excluded from using operators such as >= <=, and conditional statements

For example, nbit2s(5,3) returns 0 because the representation is impossible.

I'm not looking for any code but just for ideas, so far my idea has been:

  1. Take in number n and convert it to it's binary representation.
  2. Left Shift the binary representation 64-n times to get MSB and store that in a variable shift 3.Shift to the right 64-n to get leading bit and store in shift
  3. XOR original number with W, if 1 then TRUE, 0 then FALSE.

I feel like this is along the right lines, but if someone could explain perhaps a better way to do it or any mistakes i may have made, that would be great.

  • 2
    `long int x` may only be 32-bit. Recommend `long long` or `uint64_t`. – chux - Reinstate Monica Jan 29 '16 at 05:13
  • I was under the impression that long int was 64 bit on a mac machine and kept as 32 bit on windows machines. – Bob Dylan Jan 29 '16 at 05:16
  • 1
    I feel you're doing the same course: https://stackoverflow.com/questions/9122636/finding-how-many-bits-it-takes-to-represent-a-2s-complement-using-only-bitwise https://stackoverflow.com/questions/8204075/minimum-bits-required-for-twos-complement-number-representation – viraptor Jan 29 '16 at 05:25
  • I believe this is the answer you're looking for http://stackoverflow.com/a/16105238/1772838 – Parker Hoyes Jan 29 '16 at 05:55

2 Answers2

2

If I am understanding your question correctly, you would like to determine if the integer x can be represented as a binary number with n or less bits.

An easy way to test for this is to use the bitwise AND operator to mask out all bits above a maximum value, and then see if the masked integer is the same as the original.

Example:

bool nbit2s(uint64_t x, int n) {
    return (x & (1ULL << n) - 1) == x;
}
Parker Hoyes
  • 2,118
  • 1
  • 23
  • 38
1

A solution for positive numbers would be to just shift right by n. If it's still non-zero, then it needs more than n bits to represent it.

But since the argument is signed and you're talking about 2 complement representation, you'll probably have to cast it as unsigned representation to avoid sign extension.

viraptor
  • 33,322
  • 10
  • 107
  • 191