From the collection

FLIPPING OR MIRRORING A BYTE VALUE USING BASIC CODE

FLIPPING OR MIRRORING A BYTE VALUE USING BASIC CODE
From the personal collection

About this item

One small basic program I wrote was a program to inverse or mirror the bit values of a byte. I later used this routines to mirror a sprite.
The idea is that the lowest bits of a byte are transfered to the highest bytes and visa versa. See the following image explaining this a bit more.

If a bit is "1" in the byte then set the opposite bit in the byte to "1"
For example if the highest bit in a byte is set (value 128) then set the lowest bit (1).
I created a few different routines to accomplish this in Commodore basic.
First straightforward method (and also the fastest).

10 b = int(rnd(1)*255) : r=.
20 if b and 1 then r=128
30 if b and 2 then r=r+64
40 if b and 4 then r=r+32
50 if b and 8 then r=r+16
60 if b and 16 then r=r+8
70 if b and 32 then r=r+4
80 if b and 64 then r=r+2
90 if b and 128 then r = r +1
100 print "reversed :" r

Second method using the "power to" operator and a loop.

10 b = int(rnd(1)*255) : for n=0to7
20 if b and 2^n then r = r+2^(7-n)
30 next : print "reversed :" r , r$

This code is very short, however the method is quite slow on a Commodore.
And a third method doing the same but this time using a string representation en mid$ function.

10 b=int(rnd(1)*255)
15 r=. :b$="00000000":r$="00000000"
20 if b and 1 then  r=128:r$="1"+mid$(r$,2,8)
30 if b and 2 then  r=r+64:r$=mid$(r$,1,1)+"1"+mid$(r$,3,8)
40 if b and 4 then  r=r+32:r$=mid$(r$,1,2)+"1"+mid$(r$,4,8)
50 if b and 8 then  r=r+16:r$=mid$(r$,1,3)+"1"+mid$(r$,5,8)
60 if b and 16 then r=r+8:r$=mid$(r$,1,4)+"1"+mid$(r$,6,8)
70 if b and 32 then r=r+4:r$=mid$(r$,1,5)+"1"+mid$(r$,7,8)
80 if b and 64 then r=r+2:r$=mid$(r$,1,6)+"1"+mid$(r$,8,8)
90 if b and 128 thenr=r+1: r$=mid$(r$,1,7)+"1"
100 print "reversed :" r , r$

Collection details

PlatformCommodore 64 BASIC
← Back to BASIC Programs