Posted: 01:52pm 30 Oct 2011 |
Copy link to clipboard |
Print this post |
|
One of the wishes remaining on the firmware wishlist is for Bitwise functions. In the meanwhile, the following code sample shows MMBasic subroutine implementations of most of the bitwise operations likely to be used, viz:
NOT, SHIFTLEFT, SHIFTRIGHT, ROTATELEFT, ROTATERIGHT and a decimal-to-binary routine - DEC2BIN.
The code shows their usage and should be self-explanatory:
10 V=INT(256*RND())
20 S=1
30 ' Display of Bitwise Operations
40 CLS
50 ? "Original Decimal: ";V:? "Shift: ";S;" place."
60 ?:? "Decimal 8-bit Byte":? "---------------- ----------"
70 NUM=V:GOSUB 480 ' DEC2BIN$ Only
80 ? FORMAT$(V,"%4g"),,DEC2BIN$
90 BYTE=V:GOSUB 230 ' NOT
100 ? FORMAT$(NUM,"%4g"),,;:GOSUB 480:? DEC2BIN$, "NOT (Inverted)"
110 BYTE=V:OP=S:GOSUB 280 ' LEFTSHIFT
120 ? FORMAT$(NUM,"%4g"),,;:GOSUB 480:? DEC2BIN$,"Shifted Left"
130 BYTE=V:OP=S:GOSUB 330 ' RIGHTSHIFT
140 ? FORMAT$(NUM,"%4g"),,;:GOSUB 480:? DEC2BIN$,"Shifted Right"
150 BYTE=V:OP=S:GOSUB 390 ' ROTATELEFT
160 ? FORMAT$(NUM,"%4g"),,;:GOSUB 480:? DEC2BIN$,"Rotated Left"
170 BYTE=V:OP=S:GOSUB 430 ' ROTATERIGHT
180 ? FORMAT$(NUM,"%4g"),,;:GOSUB 480:? DEC2BIN$,"Rotated Right"
190 END
200 '
210 '
220 '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
230 ' NOT -> Invert BYTE
240 NUM=BYTE XOR 255
250 RETURN
260 '
270 '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
280 ' SHIFTLEFT -> Shift BYTE left by OP bits
290 NUM=(BYTE*2^OP) AND 255
300 RETURN
310 '
320 '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
330 ' SHIFTRIGHT -> Shift BYTE right by OP bits
340 NUM=FIX(BYTE/2^OP)
350 RETURN
360 '
370 '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
380 ' ROTATELEFT -> Rotate BYTE left by OP bits
390 NUM=((2^OP*BYTE)MOD 256) OR (BYTE>127)
400 RETURN
410 '
420 '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
430 ' ROTATERIGHT -> Rotate BYTE right by OP bits
440 NUM=(128*(BYTE AND 1)) OR FIX(BYTE/2)
450 RETURN
460 '
470 '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
480 ' DEC2BIN$ -> 8-bit binary representation of value of NUM
490 DEC2BIN$=""
500 DO WHILE NUM>0
510 DEC2BIN$=STR$(NUM MOD 2)+DEC2BIN$
520 NUM=FIX(NUM/2)
530 LOOP
540 DEC2BIN$=RIGHT$(STRING$(8,"0")+DEC2BIN$,8)
550 RETURN
|