Subj : Re: right shifting to divide To : comp.programming From : moi Date : Sun Jul 31 2005 04:24 pm 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 .