Division With Shifts

COTTRELL, JAMES cottrell at nbs-vms.arpa
Fri Jan 10 04:07:24 AEST 1986


/*
> Just shifting using an arithmetic shift may give the wrong answer, but
> you could correct the rounding and still get much faster execution like:
> 
> 	shiftRightArithmetic	register
> 	branchIfPositive	label
> 	increment		register
> label:
> 
> so -23/2 = -23>>1 + 1 = 11101001>>2 + 1 = 11110100 + 1 = 11110101 = -11
> which is the right answer...

For -23, but not in the general case. Try an even number. The code must
be like so (for the general shift case):

	Test			Target
	BranchPositive		label
	Add			2**Shiftcount - 1,Target
label:	ShiftRightArithmatic	Target,Shiftcount

So in order to divide by 2, add 1 & shift once; by 4 add three & shift 
twice; by 8 add 7 & shift thrice; etc

> 					-Miles

Miles from nowhere?

	jim		cottrell at nbs
*/
------



More information about the Comp.lang.c mailing list