12,395,203 members (61,978 online)
alternative version

68.9K views
35 bookmarked
Posted

# Number base conversion class in C#

, 22 Dec 2006
 Rate this:
Library class to convert numbers between any number bases (from 2 to 36)

## Introduction

This library class converts numbers between a variety of number bases - in fact, any number base between 2 (binary) and 36. This goes beyond the .NET framework conversion libraries which offer a limited set of conversions

The library exposes a number of common conversions (such as Binary to Decimal/base10) for simple use as well as allowing user defined conversions under advanced use (such as base 26 to base 5)

## Background

Recently I needed to calculate the numeric column ordinals for an Excel spreadsheet. Columns begin at 'A' and continue to 'B, ..., Z, AA, AB, ...' etc. I could not find any code to do this anywhere and also came across a number of posts on various coding sites asking how to perform conversions between arbitrary number bases

I solved my Excel requirement using a short function but decided it would be a useful exercise to develop a general number conversion class - this is the result. This class is generic enough to include handling the Excel scenario as well as all conventional number bases from 2 to 36 (inclusive)

The actual process of converting between bases is fairly trivial and I chose to convert to base 10 as an interim step. Therefore, when converting from base 3 to 7, for example, the code converts from base 3 to 10 then 10 to 7. I'm sure it is possible to develop a single algorithm to perform the conversion in one step so this may appear in a later version although I feel the current solution is easier to maintain and debug so maybe not

## Code structure

There are 3 projects in the attached solution:

• MarkGwilliam.com.Framework.Convert - Conversion class library
• MarkGwilliam.com.Framework.Convert.Tests - Unit tests (requires NUnit)
• MarkGwilliam.com.Framework.Convert.Demo - UI demo (see screenshot above)

## Using the code

A simple demo is included. Download the code, open the solution, set the Demo project as startup and run. This will start the UI demo which you can use for simple conversions

In your own code, the `Converter` class can be used in a number of ways:

• Simple use: built-in converters
• Advanced use: custom converters
• Advanced use: converter instances

...these are detailed below

### Simple use: built-in converters

The simplest method is to use one of the 12 built-in static converters:

• `Convert.BinToDec.Convert()`
• `Convert.BinToHex.Convert()`
• `Convert.BinToOct.Convert()`
• `Convert.DecToBin.Convert()`
• `Convert.DecToHex.Convert()`
• etc.

This allows all conversion combinations using Binary, Octal, Decimal and Hexadecimal. For example:

```// Convert FFFF (hex) to binary:

string binary = Converter.HexToBin.Convert("FFFF");```

### Advanced use: custom converters

In addition to the built-in static converters you can also perform custom conversion:

```// Convert FFFF (hex) to base 5:

string base5 = Converter.Convert(NumberBases.Hexadecimal, 5, "FFFF");```

### Advanced use: converter instances

Converter instances can also be created instead of using the built-in static converters or the static `Converter.Convert()` methods (overloaded)

Instances are created using the static `Converter.Create()` factory methods which have a number of overloads. Once an instance is created, calls can be made to the `Convert()` method to perform conversions using the number bases specified when creating the converter instance

```// base 26 (alphabet based) such as Excel column names --> decimal

Converter fromExcel = Converter.Create(26, NumberingSchemes.AToZ, NumberBases.Decimal,
NumberingSchemes.ZeroToZ);

string columnNumber = fromExcel.Convert("AA");```

## Limitations

There are a few limitations to bear in mind:

• Negative numbers are not supported
• All converted values are returned as strings
• The largest value that can be converted is `Int64.MaxValue` as `long` is used internally
• Special character denoting number bases are not supported. For instance, Hexadecimal values are often written as `0xFF01` or `&HFF01`. This class requires the simpler `FF01` notation

## Points of Interest

The download includes unit tests (requires NUnit) which, apart from validating the conversions and testing class behaviour, also shows a number of other ways to use the class

The source is liberally commented and the associated documentation file (.CHM) is included

## Further development

A couple of future plans:

• Allow use of custom numbering strings. i.e. user defined symbols to use as digits
• Support for number bases > 36

## History

• Version 1.0 - 1st Jan 2007 - Initial version

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

## About the Author

 Architect oo.magic United Kingdom
Mark Gwilliam is a freelance .Net consultant based in the UK specialising in .Net architecture, design and coding.

He has been working in IT for around 15 years and has worked primarily in the financial sector and is always keen to lead, learn, follow or teach

## Comments and Discussions

 First Prev Next
 Maximum string length Bhavesh Maniya6-Jul-15 1:47 Bhavesh Maniya 6-Jul-15 1:47
 Please post a complete code using C# Reyden Mercado Quijano1-Sep-15 0:53 Reyden Mercado Quijano 1-Sep-15 0:53
 This Version has no Size Limit Joe Monnin31-Mar-14 16:07 Joe Monnin 31-Mar-14 16:07
 Re: This Version has no Size Limit PIEBALDconsult31-Mar-14 17:07 PIEBALDconsult 31-Mar-14 17:07
 Re: This Version has no Size Limit Joe Monnin3-Apr-15 7:55 Joe Monnin 3-Apr-15 7:55
 Can find nunit.framework Member 100324516-May-13 7:40 Member 10032451 6-May-13 7:40
 Another Way of Doing the Same Thing John d. Bartels16-Jan-12 12:43 John d. Bartels 16-Jan-12 12:43
 Merci petite pomme29-Sep-11 5:21 petite pomme 29-Sep-11 5:21
 Doesn't convert zero Darchangel27-Mar-09 4:17 Darchangel 27-Mar-09 4:17
 Re: Doesn't convert zero John d. Bartels16-Jan-12 12:56 John d. Bartels 16-Jan-12 12:56
 Thank You Member 9460925-Feb-09 5:43 Member 946092 5-Feb-09 5:43
 Great ... but mahpet20-Feb-08 10:32 mahpet 20-Feb-08 10:32
 Mark - Brilliant utility class and most useful. But I hit a problem when converting base10 to base 26. It is not quite right at the threshold on AtoZ number scheme - add the following tests and you end up with "A_" appearing where "Z" should be. Converter o4 = Converter.Create(10, NumberingSchemes.ZeroToZ, 26, NumberingSchemes.AToZ); Assert.AreEqual("A", o4.Convert("1")); //Pass Assert.AreEqual("Y", o4.Convert("25")); //Pass Assert.AreEqual("Z", o4.Convert("26")); //Fail - Expected "Z" but got "A_" Assert.AreEqual("AA", o4.Convert("27")); //Pass Assert.AreEqual("ZZ", o4.Convert("702")); //Fail - Expected ZZ but got "AA_"
 Re: Great ... but MarkGwilliam21-Feb-08 8:59 MarkGwilliam 21-Feb-08 8:59
 Re: Great ... but John Simmons / outlaw programmer31-Aug-08 1:50 John Simmons / outlaw programmer 31-Aug-08 1:50
 Re: Great ... but dzCepheus26-Mar-09 8:57 dzCepheus 26-Mar-09 8:57
 Very useful class Lieven I29-Oct-07 1:05 Lieven I 29-Oct-07 1:05
 Re: Very useful class MarkGwilliam29-Oct-07 9:32 MarkGwilliam 29-Oct-07 9:32
 Similar work rvdt7-Jan-07 22:20 rvdt 7-Jan-07 22:20
 A sugestion... Vlad Stanciu23-Dec-06 22:39 Vlad Stanciu 23-Dec-06 22:39
 Nice Article PaulC197223-Dec-06 19:07 PaulC1972 23-Dec-06 19:07
 Last Visit: 31-Dec-99 18:00     Last Update: 23-Jul-16 12:25 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.