Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!kanaga.switch.ch!news-zh.switch.ch!switch.ch!news.belwue.de!not-for-mail From: Thomas Richter Newsgroups: comp.lang.java.programmer Subject: Re: Java left shift and right shift operators. Date: Sat, 30 Apr 2011 00:02:15 +0200 Organization: InterNetNews at News.BelWue.DE (Stuttgart, Germany) Lines: 44 Message-ID: References: <295e16b3-2ed8-4529-bfb0-1cc26ed93ad6@d26g2000prn.googlegroups.com> <188cz6ta97kkm$.dlg@kimmeringer.de> NNTP-Posting-Host: vpn-m-8d3a2f26.campus.uni-stuttgart.de Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.belwue.de 1304114537 16312 141.58.47.38 (29 Apr 2011 22:02:17 GMT) X-Complaints-To: news@news.belwue.de NNTP-Posting-Date: Fri, 29 Apr 2011 22:02:17 +0000 (UTC) User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.16) Gecko/20110307 Icedove/3.0.11 In-Reply-To: Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3365 On 27.04.2011 07:40, Travers Naran wrote: > On 26/04/2011 9:32 AM, Sanny wrote: >> I have computed and found "if statments" take 20-50 times longer than >> basic arithmetic operations. So I wanted to replace if condition by >> some arithmetics/ Maths. > > This is why I think assembly language should be mandatory in schools. :-) > > An if statement gets translated into something like (using a > pseudo-assembly for readability): > > ;; if (b > 0) return a << b else return a >> -b > compare b to 0 > jump-less-than to L1 > a := a << b > jump L2 > L1: > b := -b > a := a >> b > L2: > return ;; result in a Folks, this is all too complicated. As already stated, branches can kill the performance, but it is just too easy without them: (x >> r) << l. And set l = max(-s,0) and r = max(s,0) where is is the "signed right shift". If the shift is always by the same constant, it is easier to precalculate l and r once and apply the shift all over again. Alternatively, if the shift is always dynamic, l and r can also be computed without any branch: int m = (s >> 31); int r = s & m; int l = (-s) & (~m); int x = (x >> r) << l; Whether this is faster depends of course whether a branch prediction is able to predict the branches well. Greetings, Thomas