How to resolve the algorithm Non-decimal radices/Convert step by step in the C# programming language
How to resolve the algorithm Non-decimal radices/Convert step by step in the C# programming language
Table of Contents
Problem Statement
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc. For example: the decimal number 26 expressed in base 16 would be 1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Non-decimal radices/Convert step by step in the C# programming language
Overview:
This C# code provides a class, BaseConverter
, for converting numbers between different bases (2 to 36). It includes methods for converting both strings to numbers (stringToLong
) and numbers to strings (longToString
).
Method Details:
stringToLong(string s, int b)
:
- Converts a string
s
to a number in baseb
. - Validates the value of
b
to ensure it is between 2 and 36 (inclusive). - Iterates through the characters in
s
and interprets them as numeric digits. - The numeric value of each digit is calculated based on its ASCII code and the base.
- The result is multiplied by the base at each step, and the digit value is added, effectively performing the base conversion.
- Handles negative signs if they appear as the first character of
s
.
longToString(long n, int b)
:
- Converts a number
n
to a string in baseb
. - Again, validates
b
to be between 2 and 36. - Handles negative numbers by prefixing the string with a negative sign.
- Divides
n
by increasing powers ofb
until it becomes less thanb
. - Calculates the digit value by dividing
n
by the current power and converting the result to a character. - Numeric digits are represented by ASCII codes from '0' to '9', while alphabetic digits for bases greater than 10 are represented by lowercase letters from 'a' onwards.
Implementation Notes:
- The code uses checked exceptions to ensure that arithmetic operations do not overflow or underflow.
- It employs a StringBuilder for efficiency when building the output string (only available in .NET 4.0 or higher).
- The conversion logic ensures that the digits are valid for the specified base.
Source code in the csharp programming language
public static class BaseConverter {
/// <summary>
/// Converts a string to a number
/// </summary>
/// <returns>The number.</returns>
/// <param name="s">The string to convert.</param>
/// <param name="b">The base number (between 2 and 36).</param>
public static long stringToLong(string s, int b) {
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
checked {
int slen = s.Length;
long result = 0;
bool isNegative = false;
for ( int i = 0; i < slen; i++ ) {
char c = s[i];
int num;
if ( c == '-' ) {
// Negative sign
if ( i != 0 )
throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s");
isNegative = true;
continue;
}
if ( c > 0x2F && c < 0x3A )
// Numeric character (subtract from 0x30 ('0') to get numerical value)
num = c - 0x30;
else if ( c > 0x40 && c < 0x5B )
// Uppercase letter
// Subtract from 0x41 ('A'), then add 10
num = c - 0x37; // 0x37 = 0x41 - 10
else if ( c > 0x60 && c < 0x7B )
// Lowercase letter
// Subtract from 0x61 ('a'), then add 10
num = c - 0x57; // 0x57 = 0x61 - 10
else
throw new ArgumentException("The string contains an invalid character '" + c + "'", "s");
// Check that the digit is allowed by the base.
if ( num >= b )
throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s");
// Multiply the result by the base, then add the next digit
result *= b;
result += num;
}
if ( isNegative )
result = -result;
return result;
}
}
/// <summary>
/// Converts a number to a string.
/// </summary>
/// <returns>The string.</returns>
/// <param name="n">The number to convert.</param>
/// <param name="b">The base number (between 2 and 36).</param>
public static string longToString(long n, int b) {
// This uses StringBuilder, so it only works with .NET 4.0 or higher. For earlier versions, the StringBuilder
// can be replaced with simple string concatenation.
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
// If the base is 10, call ToString() directly, which returns a base-10 string.
if ( b == 10 )
return n.ToString();
checked {
long longBase = b;
StringBuilder sb = new StringBuilder();
if ( n < 0 ) {
// Negative numbers
n = -n;
sb.Append('-');
}
long div = 1;
while ( n / div >= b )
// Continue multiplying the dividend by the base until it reaches the greatest power of
// the base which is less than or equal to the number.
div *= b;
while ( true ) {
byte digit = (byte) (n / div);
if ( digit < 10 )
// Numeric character (0x30 = '0')
sb.Append((char) (digit + 0x30));
else
// Alphabetic character (for digits > 10) (0x61 = 'a')
sb.Append((char) (digit + 0x57)); // 0x61 - 10
if ( div == 1 )
// Stop when the dividend reaches 1
break;
n %= div;
div /= b;
}
return sb.ToString();
}
}
}
You may also check:How to resolve the algorithm Two's complement step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Variadic function step by step in the Python programming language
You may also check:How to resolve the algorithm Map range step by step in the Forth programming language
You may also check:How to resolve the algorithm Program name step by step in the Objective-C programming language
You may also check:How to resolve the algorithm Maze generation step by step in the Befunge programming language