Forth and number formatting

Home Forums Forth Programming Forth and number formatting

This topic contains 2 replies, has 2 voices, and was last updated by  Budsy 8 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #12815

    Budsy
    Participant

    On a Python forum I saw somebody struggling to turn an integer into a hex number formatted a particular way: b’\x0D\x20′ (for the integer 3360). This seems easy to do in Forth:

    : >HEXF ( n — addr cnt )
    BASE @ >R HEX 0
    <# ”’ HOLD # # ‘x’
    HOLD ‘\’ HOLD # # ‘x’
    HOLD ‘\’ HOLD ”’
    HOLD ‘b’ HOLD #>
    R> BASE !
    ;

    3360 >HEXF
    CR TYPE
    b’\x0D\x20′
    \ Is there a better way?

    #13750

    Mark Bratcher
    Participant

    “Better” might be a little subjective, but I would break out the formatting of a byte as hex using its own word:

    : #hexb ( d1 -- d2 )
        # # [char] x hold [char] \ hold ;

    Then write:

    : >hexf ( n -- addr cnt )
        base @ >r hex 0
        <# [char] ' hold #hexb #hexb [char] ' hold [char] b hold #>
        r> base ! ;

    So the #hexb word gives you more flexibility. If you wanted to do a more arbitrary length hex value, you could loop the #hexb execution.

    #13753

    Budsy
    Participant

    Yes, factoring is usually an improvement. I still like the new SwiftForth character constants though, which would crunch the code even more. But the [char] usage is more standard. Thanks for your contribution Mark.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.