Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit b06246a

Browse files
committed
Update to use @AlexOldest BaseConvert impl
1 parent 804d9c1 commit b06246a

File tree

1 file changed

+23
-33
lines changed

1 file changed

+23
-33
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 23 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -54,44 +54,34 @@ public static object To(this string value, Type type)
5454
/// <returns></returns>
5555
public static string BaseConvert(this string source, int from, int to)
5656
{
57-
const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
58-
var result = "";
59-
var length = source.Length;
60-
var number = new int[length];
61-
62-
for (var i = 0; i < length; i++)
57+
var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
58+
var len = source.Length;
59+
if (len == 0)
60+
throw new Exception(string.Format("Parameter: '{0}' is not valid integer (in base {1}).", source, from));
61+
var minus = source[0] == '-' ? "-" : "";
62+
var src = minus == "" ? source : source.Substring(1);
63+
len = src.Length;
64+
if (len == 0)
65+
throw new Exception(string.Format("Parameter: '{0}' is not valid integer (in base {1}).", source, from));
66+
67+
var d = 0;
68+
for (int i = 0; i < len; i++) // Convert to decimal
6369
{
64-
number[i] = chars.IndexOf(source[i]);
70+
int c = chars.IndexOf(src[i]);
71+
if (c >= from)
72+
throw new Exception(string.Format("Parameter: '{0}' is not valid integer (in base {1}).", source, from));
73+
d = d * from + c;
6574
}
75+
if (to == 10 || d == 0)
76+
return minus + d;
6677

67-
int newlen;
68-
69-
do
78+
var result = "";
79+
while (d > 0) // Convert to desired
7080
{
71-
var divide = 0;
72-
newlen = 0;
73-
74-
for (var i = 0; i < length; i++)
75-
{
76-
divide = divide * @from + number[i];
77-
78-
if (divide >= to)
79-
{
80-
number[newlen++] = divide / to;
81-
divide = divide % to;
82-
}
83-
else if (newlen > 0)
84-
{
85-
number[newlen++] = 0;
86-
}
87-
}
88-
89-
length = newlen;
90-
result = chars[divide] + result;
81+
result = chars[d % to] + result;
82+
d /= to;
9183
}
92-
while (newlen != 0);
93-
94-
return result;
84+
return minus + result;
9585
}
9686

9787
public static string EncodeXml(this string value)

0 commit comments

Comments
 (0)