Path: utzoo!attcan!uunet!lll-winken!lll-lcc!ames!nrl-cmf!cmcl2!rutgers!att!whuts!homxb!hound!rkl1 From: rkl1@hound.UUCP (K.LAUX) Newsgroups: comp.lang.c Subject: Re: Efficient coding considered harmful? Summary: shifting instead of dividing Message-ID: <2730@hound.UUCP> Date: 2 Nov 88 17:31:27 GMT References: <3105@hubcap.UUCP> <34112@XAIT.XEROX.COM> <1700@dataio.Data-IO.COM> <136@twwells.uucp> Organization: AT&T Bell Laboratories, Holmdel Lines: 45 In article <136@twwells.uucp>, bill@twwells.uucp (T. William Wells) writes: | In article <8775@smoke.BRL.MIL> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) writes: | : In article <119@twwells.uucp> bill@twwells.UUCP (T. William Wells) writes: | | : >... dividing positive numbers by powers of two should be done with a shift. | : | : No! Juggling the source code to use bit-oriented operations in an | : arithmetic context not only makes the code less portable and harder | : to maintain, it can also lead to future errors, when for example a | : chunk size is changed to a variable rather than a constant, or to a | : non-power-of-two. | | Less portable? | | If a compiler doesn't take my n >> m (n >= 0, m < 16) and do | the same thing as when dividing it by 2**m, the compiler is | broken. Now, there might be some compilers that are broken | that way, but that makes it an individual decision as to | whether one panders to the frailties of those compilers. For | the record, the spelling code I earlier mentioned does this in | a few places and I've never heard of a problem relating to it. | I'm suprized that noone has questioned the validity of shifting instead of dividing by (powers of) 2. What about the difference between Logical and Arithmetic shifts? If you want to divide, then divide! A lot of compilers are smart enough to implement the divide as a shift, but only where appropriate. I *did* notice the condition of dividend being positive, but now you have to *guarantee* that it will always be positive. Also, by implication, the dividend is a *signed* quantity. You can get into trouble if it gets changed to an *unsigned* quantity (like when 16K isn't enough). As for the 'compiler being broken' if it doesn't do the same thing for a shift and dividing, this is not true. In one case, you only told it to shift, the other to do a divide: they made be *equivalent*, but they certainly are not *equal*. So, please, if you *functionally* require a divide by (powers of) 2, code it as a divide and let the compiler *implement* it (maybe optimization needs to be turned on). --rkl