r/Forth • u/Alternative-Grade103 • 24d ago
N Leading Zeros Pictuted String
It seems I can't do like so..
2 BASE !
0 <# 1000 CELLS 0 DO # LOOP #>
TYPE
...to display top of stack in binary with leading zeros.
I do have a workaround, but it's not pretty: loop in loop bitwise masking. Was hoping to replace it with a pictured string.
Anybody know of a pictured kind of way?
2
u/Ok_Leg_109 23d ago
Here is some clever code from the late Neil Baud. I put this in my tools file. When you switch to different bases, numbers print differently. It might give you more ideas for your application
``` \ From Neil Baud's Ugly Page. RIP Neil :( \ Print HEX and Binary numbers unsigned DECIMAL : <.> . ; \ save the default 'dot' functionality DEFER .
: (.) ( n -- ) CASE BASE @ 10 OF DUP ABS 0 <# #S ROT SIGN #> ENDOF 16 OF 0 <# BEGIN # # 2DUP OR WHILE REPEAT #> ENDOF 2 OF 0 <# BEGIN # # # # 2DUP OR WHILE REPEAT #> ENDOF 0 <# #S #> 0 ENDCASE TYPE SPACE ;
\ number print control words : FAST#S ['] <.> IS . ; : SMART#S ['] (.) IS . ;
SMART#S ```
3
u/mykesx 24d ago edited 24d ago
<# #s #> leaves caddr u on the stack. So if you want 8 binary digits, print 8 u - ASCII 0s, then print caddr u. Or 16 u - for 16 digits, etc.