f



right shifting to divide

Hi, I am reading 'Lion's Commentary on UNIX', and I am wondering about a
small bit of code, which is as follows:

/*
 * Return the arg/128 rounded up.
 */

nseg(n)
{

  return((n+127)>>7);
}

It is found on sheet 16 beginning at line 1768, for anyone who might have
the book.  Anyway, I curious as to the adding of 127 to the number, and
then the right shift.  I realise that it divides the number roughly by two,
but I am still kind of foggy as to the methodology.  Why add 127 then right
shift by 7?  Why not just right shift by 1?

Rob Somers
0
7/31/2005 1:01:36 PM
comp.programming 11491 articles. 2 followers. Post Follow

2 Replies
303 Views

Similar Articles

[PageSpeed] 19

Rob Somers wrote:
> Hi, I am reading 'Lion's Commentary on UNIX', and I am wondering about a
> small bit of code, which is as follows:
> 
> /*
>  * Return the arg/128 rounded up.
>  */
> 
> nseg(n)
> {
> 
>   return((n+127)>>7);
> }

It returns n/128, rounded up. That's what is says.

> It is found on sheet 16 beginning at line 1768, for anyone who might have
> the book.  Anyway, I curious as to the adding of 127 to the number, and
> then the right shift.  I realise that it divides the number roughly by two,
> but I am still kind of foggy as to the methodology.  Why add 127 then right
> shift by 7?  Why not just right shift by 1?

Because that would divide by two.

return (n+1) >>1; /* n/2, rounded up */

Note: unwanted results may occur, when n is negative.

HTH,
AvK
0
moi
7/31/2005 1:24:45 PM
> It returns n/128, rounded up. That's what is says.

doh!  It was right under my nose - I am not sure why I was thinking 'divided
by two' but it was certainly clouding my judgement..

> Because that would divide by two.
> 
> return (n+1) >>1; /* n/2, rounded up */
> 
> Note: unwanted results may occur, when n is negative.
> HTH,
> AvK

Thanks
0
7/31/2005 4:01:32 PM
Reply: