Skip to content

Instantly share code, notes, and snippets.

@crcx
Created May 25, 2017 19:57
Show Gist options
  • Select an option

  • Save crcx/ff5a3af0f16baf6e1a2a61cbe8f4d0ea to your computer and use it in GitHub Desktop.

Select an option

Save crcx/ff5a3af0f16baf6e1a2a61cbe8f4d0ea to your computer and use it in GitHub Desktop.
New `s:to-number` for Retro 12

The standard string to number conversion in Retro only supports decimal values. But it's pretty easy to extend this to handle arbitrary bases.

#10 'Base var<n>

:digit (c-s)
  '0123456789ABCDEF swap s:index-of ;

:s:to-number (s-s)
  #0 swap [ digit + @Base * ] s:for-each @Base / ;

And some simple words to switch base:

:unary    #1 !Base ;
:binary   #2 !Base ;
:trinary  #3 !Base ;
:octal    #8 !Base ;
:decimal #10 !Base ;
:hex     #16 !Base ;

Some tests:

decimal
'103 s:to-number putn nl

unary
'1 s:to-number putn nl
'11 s:to-number putn nl
'111 s:to-number putn nl
'1111 s:to-number putn nl
'11111 s:to-number putn nl

binary
'11 s:to-number putn nl
'101 s:to-number putn nl

hex
'FF s:to-number putn nl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment