Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: Java left shift and right shift operators. Date: Tue, 26 Apr 2011 11:24:31 -0400 Organization: albasani.net Lines: 34 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=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net VNrUZWV2TZCSF+v6rkmNxgjTmywcpeQFytZV5wYsNwmpQWhIc3s0H0Te4SyVNzPzdL0SwLiMghYz9/E1jSUEqQ== NNTP-Posting-Date: Tue, 26 Apr 2011 15:24:26 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="wf6jFb0iCZjTa12ZOqQHThNva1hJYxRFfqdKgxJLVte3yQT4/v9qxIB6V7i1qPF0pWacpqzfklEN3CyH4eyIUTMwvYUpkjbN4nX2vBI4AzM38YEe6DszN6VjzMhEcmR+"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.14) Gecko/20110223 Thunderbird/3.1.8 In-Reply-To: Cancel-Lock: sha1:Xu+nBYP45Fww4gZVy+ZQVp6q5Ps= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3268 Travers Naran wrote: > 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); Please follow Java naming conventions. >> 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: Doesn't matter, the Java operator *is* defined for negative values. So the solution to Sanny's problem is: output = n >> shiftBy; -- Lew Honi soit qui mal y pense. http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg