From 305b4dbc423285c533a6fc1a0d9eea2e25cd6c01 Mon Sep 17 00:00:00 2001 From: crc Date: Sun, 22 Oct 2017 17:04:57 +0000 Subject: [PATCH] String to Number example now goes from number to string as well FossilOrigin-Name: 053b04070704ba62ee6cbbe8232567cf790f439634e4f74495f60f52ea8e35c4 --- example/StringToNumberWithBase.forth | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/example/StringToNumberWithBase.forth b/example/StringToNumberWithBase.forth index d001c06..80bab92 100644 --- a/example/StringToNumberWithBase.forth +++ b/example/StringToNumberWithBase.forth @@ -46,3 +46,26 @@ here is: #0 !Number check-sign [ convert ] s:for-each @Number @Mod * ; }} ~~~ + +Going the other way, back to a string, follows a similar process. + +- Take a value +- Repeat: + - Divide by `Base` + - Convert result to character and append to a buffer + - If remainder is not zero, repeat +- If number is negative, append the '-' symbol to the buffer +- Reverse the buffer contents to return a string in the correct order + +~~~ +{{ + 'String d:create #12 allot + :check-sign (n-) n:negative? [ $- buffer:add ] if ; + : n->digit (n-c) &DIGITS + fetch ; + :convert (n-) [ @Base /mod swap n->digit buffer:add dup n:zero? ] until drop ; +---reveal--- + :n:to-string (n-s) + [ &String buffer:set dup n:abs convert check-sign ] buffer:preserve + &String s:reverse ; +}} +~~~