Extended base conversion

By Sigh_ on Sep 17, 2004

Extended base conversion by Sigh (http://xi.ma.cx)
Allows conversions between any base of any given number system

Usage: $xbase(N,inbase,outbase,[zeropad],[precision],[system],[apio])

Works just like $base but allows you to specify a number system to handle. If none is specified it defaults to 0-9 A-Z a-z ("base 62")

The parameters must be specified in the order that they're shown above but the ones enclosed in brackets can be optional

The last parameter are the switches and must be specified if you've included one of the optional parameters:

a = specifies a zeropad has been given

p = specifies a precision has been given

i = inbase uses the given system

o = outbase uses the given system

If i and o are not specified the normal system is used with the corresponding bases i.e. $xbase(123,10,3,mysystemhere,o) only uses
base 3 of the system "mysystemhere" as the outbase, and regular base 10 system for the inbase so it returns: yyysm

To reverse the conversion you'd specify yyysm as N and use 3 as the inbase along with the i switch this time, so you'd want
$xbase(yyysm,3,10,mysystemhere,i) which gives the expected 123

A couple of examples to demonstrate its usage:

$xbase(111,10,10,1234567890,o) = 222

Uses the number system 1234567890 for the outbase conversion but the standard 0123456789 (base 10) for the inbase

$xbase(14.15,6,56,4,5,ap) = 000A.H6COn

Converts 14.15 in base 6 to a value in base 56 (0-9 A-Z a-t), zeropads it to 4 places and uses a precision of 5

$xbase(_iggch_g,11,10,Sigh_rocks!,i) = 80081355

Converts the string _iggch_g which uses base 11 of the system "Sigh_rocks!" as the inbase, to a number in standard base 10

alias xbase {
  if ($istok($2 $3,1,32)) return
  var %m,%b,%x,%w,%n = $gettok($1,1,46),%d = $gettok($1,2,46),%g = $len(%n),%y = $len(%d),%o = $($ $+ $0,2),%a = $iif(a isin %o,$4,1),%t = 1, $&
    %p = $iif(p isin %o,$iif(a isin %o,$5,$4),18),%s = $iif(i isin %o || o isin %o,$iif(p isin %o && a isin %o,$6,$iif(p isin %o || a isin %o,$5,$4))), $&
    %z = 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz,%i = $iif(i isin %o,%s,%z),%o = $iif(o isin %o,%s,%z)
  while (%g) { inc %x $calc(($poscs(%i,$mid(%n,%g,1))-1)*$2 ^($len(%n)-%g)) | dec %g }
  while (%x) var %m = $mid(%o,$calc(1+%x % $3),1) $+ %m,%x = $int($calc(%x /$3))
  while (%y) { inc %w $calc(10^18 *($poscs(%i,$mid(%d,%y,1))-1)*$2 ^-%y) | dec %y }
  while (%t <= %p) && (%w) { var %r = $int($calc(%w *$3 ^%t /10^18)),%b = %b $+ $mid(%o,$calc(1+%r),1) | dec %w $calc(%r *10^18 / $3 ^%t) | inc %t }
  return $+($str(0,$calc(%a -$len(%m))),%m,$iif(%b,. $+ %b))
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.