1.11M Members

Check if value fits in n-bit integer

 
0
 

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;
}
 
0
 

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.

 
0
 

Take a close look at line 25. Are you sure you want a shift to be logical?

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article