i writing function parameters:
int nbit2s(long int x, long int n){ }
i looking take in 64 bit number x, , find if 2 bit representation of n bit length possible. restricted using bitwise operators , excluded using operators such >= <=, , conditional statements
for example, nbit2s(5,3) returns 0 because representation impossible.
i'm not looking code ideas, far idea has been:
- take in number n , convert it's binary representation.
- left shift binary representation 64-n times msb , store in variable shift 3.shift right 64-n leading bit , store in shift
- xor original number w, if 1 true, 0 false.
i feel along right lines, if explain perhaps better way or mistakes may have made, great.
if understanding question correctly, determine if integer x
can represented binary number n
or less bits.
an easy way test use bitwise , operator mask out bits above maximum value, , see if masked integer same original.
example:
bool nbit2s(uint64_t x, int n) { return (x & (1ull << n) - 1) == x; }
Comments
Post a Comment