I am doing this assignment for my computer science course, and I have to write a function that determines if 'x' can fit into an n-bit, two's complement integer.

I am not allowed to use any control statements or operators other than the ! ~ & ^ | + << >> operators. I am also not allowed to use any macros or function calls. I am also not allowed to use any form of casting or any variables that are not of type int, including arrays, structs and unions.

This is assuming a 32-bit, two's complement integers.

This is the code I have written so far. I doesn't really work well, and I can't find what I am doing wrong, any help would be appreciated.

This function is supposed to check if an integer with the 
value of 'x' would fit inside an integer with a 'n' bits

Returns non-zero is 'x' fits in a integer with 'n' bits
Returns zero if it doesn't
int fitsBits(int x, int n)
	//declare variables
	int sv, tx;

	//this calculates the 32 - (n + 1)
	//this is the value to shift 'x' to calculate 'tx'
	sv = 32 + (~n);
	//shift 'x' left sv bits and assigns it to 'tx', 
	//this is later shifted back the same amount
	//this is done so that 'tx' will equal
	//a version of 'x' that is truncated to fit in 'n' bits
	tx = x << sv;
	//make sure leftmost bit is zero
	//(to make sure right shift is equivalent to logical shit)
	tx = tx & ~(0x01 << 31);

	//shift 'tx' back
	tx = tx >> sv;

	//calculate bitwise xor of tx and x
	//this checks if there are any bits are outside of the range designated by 'n'	
	return tx ^ x;

Edited by chrjs: n/a

7 Years
Discussion Span
Last Post by mbelenske

Well, I found that I needed to change line 32 to return !(tx ^ x); , but the program doesn't work for negative numbers. It would be appreciated if anyone could give me an idea on how to account for the sign in this problem.

Edited by chrjs: n/a


My working Code. I believe if you remove line 25 it should work.

int fitsBits(int x, int n) 
        int a = (33 + (~n));
        int b = (x << a);
        int c = (b >> a);
        int e = !(c ^ x);
        return  e;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.