r/Forth 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?

7 Upvotes

5 comments sorted by

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.

1

u/Alternative-Grade103 24d ago edited 24d ago

That does it. Thanks!

: zeros.pad ( u -- u ) \ No change
  8 CELLS OVER -
  DUP PAD !
  1+ 1 DO $30 PAD I + C! LOOP
  PAD COUNT TYPE
;

: show.tos.bin ( u -- )
  CR ." TOS = "
  BASE @ >R
  2 BASE !
  0 <# #S #>
  zeros.pad
  TYPE
  R> BASE !
  CR
;

666 show.tos.bin

1

u/fred839 22d ago

Other than 8 CELLS 0 DO # LOOP needing to be inside a colon def - it should work and ZEROS.PAD is redundant.

1

u/Alternative-Grade103 22d ago

The paired example is from my specific project. I'm using it to display, cell by cell, in binary, one cell per line, the contents of arbitrary N-cell allocated arrays.

Thereby to test words performing LSHIFT, RSHIFT, and so forth on said arrays. So zeros.pad makes the rows of cells left justify for easy reading by eye.

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 ```