newLISP Fan Club

Forum => Anything else we might add? => Topic started by: maq on September 30, 2006, 04:00:46 PM

Title: bit operation example from K+R vs. newlisp
Post by: maq on September 30, 2006, 04:00:46 PM
I was perusing through K+R "The C Programming Language" and came across this tidbit on bit operations:



(//%3C/s%3E%3CURL%20url=%22http://www.angrypacket.com/~maq/getbits.png%22%3Ehttp://www.angrypacket.com/~maq/getbits.png%3C/URL%3E%3Ce%3E)



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):



(//%3C/s%3E%3CURL%20url=%22http://www.angrypacket.com/~maq/p-n.png%22%3Ehttp://www.angrypacket.com/~maq/p-n.png%3C/URL%3E%3Ce%3E)



(p + 1 - n):



(//%3C/s%3E%3CURL%20url=%22http://www.angrypacket.com/~maq/p+1-n.png%22%3Ehttp://www.angrypacket.com/~maq/p+1-n.png%3C/URL%3E%3Ce%3E)



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
Title:
Post by: Lutz on October 03, 2006, 05:31:52 PM
I guess this is a offset 0 versus offset 1 confusion:


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