Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Travers Naran Newsgroups: comp.lang.java.programmer Subject: Re: Java left shift and right shift operators. Date: Tue, 26 Apr 2011 07:30:38 -0700 Organization: A noiseless patient Spider Lines: 32 Message-ID: References: <295e16b3-2ed8-4529-bfb0-1cc26ed93ad6@d26g2000prn.googlegroups.com> <1b558330-ae94-4e4e-9922-a9aeb63eaf37@d19g2000prh.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 26 Apr 2011 14:30:39 +0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="mZwD6WroWf8ZiutQVyui4A"; logging-data="5636"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Caap1E6BH+/8UrUJm8sMV" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.15) Gecko/20110303 Lightning/1.0b2 Thunderbird/3.1.9 In-Reply-To: <1b558330-ae94-4e4e-9922-a9aeb63eaf37@d19g2000prh.googlegroups.com> Cancel-Lock: sha1:AcIPFkdSZ6Ba4F69gu0Q8t++Fa8= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3266 On 26/04/2011 2:04 AM, Sanny wrote: >> Is there any way to avoid the if condition and do right shift and left >> shift using operators depending on shiftby is +ve or -ve? > > I used below technique but it gives error. > > divider=Math.pow(2,shiftby); > then > output = (long) N / divider; My advice: if (shift>0) output = N >> shiftby; else output = N << (-shiftby); The above is pretty efficient, and once the hotspot compiler gets a hold of it, it will be even faster. There is no assembly operator that shifts based on +/- bits; there are only shift-left and shift-right operators. If there was a Java operator/function to do what you want, it would still be implemented (in machine language) as: if (shift>0) output = N >> shiftby; else output = N << (-shiftby); But I am curious why you consider the "if" test is expensive? The usual rules for optimization: 1. Profile your code 2. Determine where your code is spending most of its time 3. Re-visit your algorithm and decide if you are using the right algorithm. 3a. If so, optimize the methods that are consuming most of the time. 3b. Implement a better algorithm and repeat these processes.