From mboxrd@z Thu Jan 1 00:00:00 1970 To: Fans of the OS Plan 9 from Bell Labs <9fans@9fans.net> In-reply-to: Your message of "Wed, 21 Apr 2010 15:40:19 +0200." <20100421134019.GA1382@polynum.com> References: <20100421134019.GA1382@polynum.com> From: Bakul Shah Date: Wed, 21 Apr 2010 16:28:52 -0700 Message-Id: <20100421232852.5AB865B4A@mail.bitblocks.com> Subject: Re: [9fans] Integer arithmetic: some lessons Topicbox-Message-UUID: 0b89a5e6-ead6-11e9-9d60-3106f5b1d025 On Wed, 21 Apr 2010 15:40:19 +0200 tlaronde@polynum.com wrote: > Hello, > > Still about integer arithmetic. ... > Conclusion (apparently): gcc always translate div involving power of two > to binary manipulations, while (apparently) ken-cc does not. gcc may choose to implement / with appropriate shifts and what not but the result must be equivalent. It certainly can't replace %2 with >>1 for negative numbers. Try this: int f(int x) { return x / 2; } int g(int x) { return x >> 1; } main(int argc, char** argv) { int x = argc > 1? atoi(argv[1]) : -7; printf("%d %d\n", -7/2, -7>>1); printf("%d %d\n", f(-7), g(-7)); printf("%d %d\n", f(x), g(x)); } This will give you -3 -4 -3 -4 -3 -4 I don't have a way to test what kencc does but I would be surprised if the result is any different.... >> is an arithmetic shift for signed numbers (the sign bit is replicated). The clearest way to see this is to compare -1/2 and -1>>1 The first gives you 0. The second gives you -1 (on twos complement machines). IIRC, Pascal's div operator behaves the same as C's / for integers. May be the problem is somehow related to mod? > Conclusion: I will have to replace in METAFONT all div involving power > of two to binary operations, since if I replace in some places and not > in others, I wreak havoc the algorithms since computations are not done > the same way for combined chunks. Replacing div 2^N of a signed number by >>N seems like a mistake.