# Converting from One Base to Another

## Problem

You need to convert strings representing numbers in some base to numbers in another base.

## Solution

This example provides a general solution for converting from any base between 2 and 36 to any base in the same range. It uses two global variables to encode the value of all characters in a base 36 system as offsets into the string—one for uppercase encoding and the other for lowercase:

```<xsl:variable name="math:base-lower"
select="'0123456789abcdefghijklmnopqrstuvwxyz'"/>

<xsl:variable name="math:base-upper"
select="'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>

<xsl:template name="math:convert-base">
<xsl:param name="number"/>
<xsl:param name="from-base"/>
<xsl:param name="to-base"/>

<xsl:variable name="number-base10">
<xsl:call-template name="math:convert-to-base-10">
<xsl:with-param name="number" select="\$number"/>
<xsl:with-param name="from-base" select="\$from-base"/>
</xsl:call-template>
</xsl:variable>
<xsl:call-template name="math:convert-from-base-10">
<xsl:with-param name="number" select="\$number-base10"/>
<xsl:with-param name="to-base" select="\$to-base"/>
</xsl:call-template>
</xsl:template>```

This template reduces the general problem to two subproblems of converting to and from base 10. Performing base 10 conversions is easier because it is the native base of XPath numbers.

The template `math:convert-to-base-10` normalizes the input number to lowercase. Thus, for example, you treat `ffff` hex the same as `FFFF` hex, which is the normal convention. ...

Get XSLT Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.