Name: baseConvert

Type: function

Syntax: baseConvert(<number>, <originalBase>, <destinationBase>)

Summary: Converts a number from one base to another.

Introduced: 1.0

OS: mac,windows,linux,ios,android

Platforms: desktop,server,web,mobile

Example:
baseConvert(16,10,2) -- yields 10000, which is 16 in base 2

Example:
baseConvert(27,10,16) -- yields 1B, which is 27 in base 16

Example:
baseConvert("1C",16,10) -- yields 28, the base-10 equivalent of 1C

Parameters:
number: The number to be converted, expressed in its original base. The number must be an integer between zero and 4,294,967,295 (2^32 - 1). If the number includes non-digits (as, for example, a base-16 number can include letters A-F), enclose the number in quotes.
originalBase (integer): An integer between 2 and 36.
destinationBase (integer): An integer between 2 and 36.

Returns: The <baseConvert> function <return|returns> a number, expressed in the <destinationBase>.

Description:
Use the <baseConvert> function to provide input or output of numbers in a base other than base 10: for example, in <hexadecimal> (base 16) or <binary> (base 2).

The everyday decimal number system is called "base 10" because we count from 1 to 9, and the tenth digit moves over to the tens place and is written 10: one group of ten, plus zero extra ones. Similarly, a number like 384 means one group of a hundred (10^2), plus eight groups of ten, plus four leftover ones.

It is possible to write numbers in other bases. For example, suppose you want to write the number six in base 4. In base 4, we count from 1 to 3, and the fourth digit moves over to the "fours place". So the numbers from one to six, in base 4, are written "1, 2, 3, 10, 11, 12". The number 12 in base 4 means one group of four, plus two leftover ones. This same number is written as 6 in base 10.

If the base is greater than 10, then digits greater than 9 are expressed as capital letters: A is the digit ten, B is the digit eleven, and so on.

LiveCode always does math in base 10, so if you want to perform mathematical calculations such as addition on a number in another base, you must first convert the number to base 10, do the calculation, then convert back to the original base. Here is an example:

  function hexSum firstAddend, secondAddend
    -- adds together two hexadecimal numbers
    put baseConvert(firstAddend,16,10) into convertedAddend1
    put baseConvert(secondAddend,16,10) into convertedAddend2
    put convertedAddend1 + convertedAddend2 into baseTenSum
    return baseConvert(baseTenSum,10,16)
  end hexSum

References: convertOctals (property), bitNot (operator), exp (function), URLDecode (function), format (function), binary (glossary), hexadecimal (glossary), return (glossary)

Tags: math
