Converting a number to a string. 4tH 4tH Forth compiler
Quảng cáo
Quảng cáo
CHAPTER 9. CHARACTER SEGMENT 102
# # .0002$
Then we want to print a dot. This is where ’HOLD’ comes in. ’HOLD’ takes an ASCII code and places the equivalent character in the formatting string. We don’t have to look up the ASCII code for a dot of course. We can use ’CHAR’:
# # char . hold 0002$
Then we want to print the rest of the number (which is at least one digit):
# # char . hold #s $
Finally we want to print the character "$". Another job for ’HOLD’:
# # char . hold #s char $ hold
So this is our formatting word:
: currency <# # # char . hold #s char $ hold #> type cr ;
And we call it like this:
200016 currency
You can do some pretty complex stuff with these formatting words. Try to figure out this one from the master himself, Leo Brodie:
: sextal 6 base ! ;
: :00 # sextal # decimal 58 hold ;
: time# <# :00 :00 #S #> type cr ;
3615 time#
Yeah, it prints the time! Pretty neat, huh? Now try the telephone-number we discussed in the beginning. That shouldn’t be too hard.
9.9
Converting a number to a string
Since there is no special word in 4tH which will convert a number to a string, we’ll have to create it ourselves. In the previous section we have seen how a numeric string is created in the PAD. We can use this to create a word that converts a number to a string.
Because the PAD is highly volatile, we have to save the string immediately after its creation.
So we’ll create a word that not only creates the string, but places it directly in its proper location:
( n a -- )
: n>string >r dup abs <# #s sign #> r> place ;
It takes a number, the address of a string and returns nothing. Example:
16 string num$
-1024 num$ n>string num$ count type cr
Tải xuống
Quảng cáo