Forth and number formattingHome › Forums › Forth Programming › Forth and number formattingTagged: Number Formatting conversion PythonThis 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 March 15, 2018 at 2:41 AM #12815 BudsyParticipantOn 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? April 10, 2018 at 7:51 AM #13750 Mark BratcherParticipant“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. April 10, 2018 at 10:50 AM #13753 BudsyParticipantYes, 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.Author Posts Viewing 3 posts - 1 through 3 (of 3 total)You must be logged in to reply to this topic.