BBS: Inland Empire Archive Date: 04-18-92 (09:24) Number: 126 From: MATT HART Refer#: NONE To: MELVIN PARKER Recvd: NO Subj: Bit Shifting Conf: (2) Quik_Bas
MP> Does anyone know how to shift bits right or left using qbasic or MS MP> Basic 7.0? I want to do this without calling another language. In my prior message - I was telling Daryl about prototyping in BASIC then converting to assembly - and one of those things was a bit shifting routine to properly align left justified fonts to the screen bitmap. I had to shift bits to do it. Here's one : shift left: A$ = " " Segment = VARSEG(A$) Offset = PEEK(VARPTR(A$)+2) A% = 255 Segment = VARSEG(A%) Offset = VARPTR(A%) SUB ShiftLeft(Segment,Offset,NumBits) DEF SEG = Segment Z = PEEK(Offset) DEF SEG FOR i = 1 TO NumBits A = (((64 AND Z) = 64) AND 128) +_ (((32 AND Z) = 32) AND 64) +_ (((16 AND Z) = 16) AND 32) +_ (((8 AND Z) = 8) AND 16) +_ (((4 AND Z) = 4) AND 8) +_ (((2 AND Z) = 2) AND 4) +_ (((1 AND Z) = 1) AND 2) Z = A NEXT DEF SEG = Segment POKE Offset,Z END SUB Now the explanation: the boolean expressions test the bits and return either -1 (a number with ALL bits set) or 0 (no bits set). Then ANDing this result with the new bit to set will either result in a bit set (if the boolean was -1) or not set (if 0). Example, if Z was equal to 68, then here's the bit pattern: 01000100 Now the expression: 64 AND Z will return 64 since bit 7 is set. Continuing, (64 AND Z) = 64 will return TRUE, since 64 AND Z returns 64. True is -1, which has the bit pattern 11111111 (actually 16, but 8 here for simplicity). Now the rest of the expression: (((64 AND Z) = 64) AND 128) The added AND 128 will return 128, since bit 8 is set in - 1. This effectively shifts bit 7 to bit 8. To shift TWO bits at a time, you can: A = (((32 AND Z) = 32) AND 128) This shifts bit 6 (32) to bit 8 (128). To shift left: A = (((128 AND Z)=128) AND 64) 1 bit to the right. --- * Origin: Midnight Micro! V.32/REL (918)451-3306 (1:170/600)
Books at Amazon:
Back to BASIC: The History, Corruption, and Future of the Language
Hackers: Heroes of the Computer Revolution (including Tiny BASIC)
Go to: The Story of the Math Majors, Bridge Players, Engineers, Chess Wizards, Scientists and Iconoclasts who were the Hero Programmers of the Software Revolution
The Advent of the Algorithm: The Idea that Rules the World
Moths in the Machine: The Power and Perils of Programming
Mastering Visual Basic .NET