As a fun puzzle I looked at different ways to reverse the binary representation of a byte completely with basic code. There are several examples of this to do this by using assembler but how to do this in basic?, well this is what I came up with.
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
1 | 0 | 1 | 1 | 0 | 0 | 0 | 1 |
If you calculate the byte value that would be 128+32+16+1= 177
Reversing or flipping this will give
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
1 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |
Calculated byte value 128+8+4+1= 141
It is also a nice exercise to work with the different string editing instructions from Commodore Basic.
Nice puzzling with bits and bytes, I have made a number of different versions from straightforward solution to a shortened version with a FOR NEXT loop.
Below is the final version that also shows the original and result in bit form by building it in a string. On my blog you can find the other versions.
1 2 3 4 |
10 b=int(rnd(1)*255) : r$="" :o$="00000000" :sb=. 20 for n=0to7:if b and 2^n then r = r+2^(7-n) : sb=1 60 r$=r$+mid$("01",1+sb,1):o$=left$(o$,7-n)+mid$("01",1+sb,1)+right$(o$,1+n) 70 sb=.:next:?"original byte value:" b,left$(o$,8):?"reversed byte value:"r,r$ |
Before I was able to create this version I experimented with the following;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
0rem ---------------------------------- 1rem --- reversing order the bits in 2rem --- a byte (straightforward) 3rem ---------------------------------- 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 |
1 2 3 4 5 6 7 8 |
0rem ---------------------------------- 1rem --- reversing order the bits in 2rem --- a byte (using a loop) 3rem ---------------------------------- 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$ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
rem -------------------------------------------------------------------- rem --- reversing order the bits in a byte - show string representation rem -------------------------------------------------------------------- 10 b = int(rnd(1)*255): 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$ |
No responses yet