Author: Bruce Moreland
Date: 12:50:43 11/29/00
Go up one level in this thread
On November 29, 2000 at 05:55:26, Jeremiah Penery wrote:
>On November 29, 2000 at 04:38:33, Eugene Nalimov wrote:
>
>>On November 29, 2000 at 02:53:42, Jeremiah Penery wrote:
>>
>>>On November 28, 2000 at 23:59:14, Ed Schröder wrote:
>>>
>>>>Especially multiplies has been improved dramatically in the latest
>>>>generation of processors. Nowadays it is hardly an issue anymore. I
>>>>still use << where ever I can but I have no problems to use * so now
>>>>and then.
>>>
>>>It seems like compilers should produce the same assembly code for things like
>>>a<<1 and a*2, but of course I'm not sure if they do. Ditto for a>>1 and a/2.
>>>(and also <<2 = *4, etc.)
>>
>>Of course a>>1 and a/2 should generate different code (hint: check value of both
>>expressions for a == -1).
>
>I ignored the negative numbers. :P
You can't ignore negative numbers if you are dealing with ints, because ints are
signed.
>First, a question: If you divide 1 by 2 and have to return an int, is 1 or 0
>returned?
1/2 = 0.
>If 0 is returned in the above, then to assembly for a>>1 and a/2 should be the
>same if a is unsigned, correct? If 1 is returned, then it seems like it would
>work for all cases except when a==1. Please correct me again if I'm wrong. :)
They will produce the same values on signed ints. If you use unsigned values, a
/ 2 will be compiled by the Microsoft compiler I use as:
shr eax, 1
If you use an signed value, you get:
cdq
sub eax, edx
sar eax, 1
This is an attempt to avoid a divide, but it's a lot of evil stuff compared with
the first one. I bet "cdq" annoys the processor, but I don't know for sure, and
in any case that's three instructions compared with one.
So if you know you have a positive value if your signed int, I think that you
should use a >>= 1 to divide it by two. I wouldn't cast it to unsigned in order
to do "a = (int)((unsigned)a / 2)" or whatever the compiler will like instead,
because it's not a good practice to using casting as a mathematical operator.
bruce
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.