bit operation example from K+R vs. newlisp

For the Compleat Fan
Locked
maq
Posts: 7
Joined: Tue Jan 18, 2005 6:20 am
Contact:

bit operation example from K+R vs. newlisp

Post by maq »

I was perusing through K+R "The C Programming Language" and came across this tidbit on bit operations:

Image

And the (p + 1 - n) doesn't make sense, as it would seem you actually want to do (p - n). I wrote the same function in newlisp both ways:

(p - n):

Image

(p + 1 - n):

Image

And the (p - n) is the one behaving as I would expect. What am I missing here? Am I not understanding K+R properly in their example? I couldn't imagine that this is a typo.

Any insights to clear my confusion would be greatly appreciated.

--maq

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

I guess this is a offset 0 versus offset 1 confusion:

Code: Select all

10 0001 1100 ; binary 540
98 7654 3210
7 picks from bits 432 and
3 from bits 542

The 'C' language normally works with 0 offset so I believe the K&R text is correct starting at the 6th bit, which is at offset 5, thats why they are adding 1, because they have to shift out 6 bits in total. So 3 is the correct result with shifting (>> bfield (- (+ pos 1) n)) .

Lutz

Locked