我给自己提供的这个解决方案看起来很有效 - 太简单了!但那是因为它是单向转换;其他图书馆的目标是在不同基地之间来回转换,但我不需要两种方式。
Public Class BaseConverter
Public Shared Function ConvertToBase(num As Integer, nbase As Integer) As String
Dim retval = ""
Dim chars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
' check if we can convert to another base
If (nbase chars.Length) Then
retval = ""
End If
Dim r As Integer
Dim newNumber As String = ""
' in r we have the offset of the char that was converted to the new base
While num >= nbase
r = num Mod nbase
newNumber = chars(r) & newNumber
'use: num = Convert.ToInt32(num/nbase)
'(if available on your system)
'otherwise:
num = num \ nbase
' notice the back slash \ - this is integer division, i.e the calculation only reports back the whole number of times that
' the divider will go into the number to be divided, e.g. 7 \ 2 produces 3 (contrasted with 7/2 produces 3.5,
' float which would cause the compiler to fail the compile with a type mismatch)
End While
' the last number to convert
newNumber = chars(num) & newNumber
Return newNumber
End Function
End Class
我创建Visual Basic中的上述代码基于在下面的链接C#代码:
CREDIT:http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/5babf71f-4375-40aa-971a-21c1f0b9762b/ (“从十进制(基-10)至字母数字转换(基数36) “)
public String ConvertToBase(int num, int nbase)
{
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// check if we can convert to another base
if(nbase chars.Length)
return "";
int r;
String newNumber = "";
// in r we have the offset of the char that was converted to the new base
while(num >= nbase)
{
r = num % nbase;
newNumber = chars[r] + newNumber;
num = num/nbase;
}
// the last number to convert
newNumber = chars[num] + newNumber;
return newNumber;
}
@assylias我不能让devx.com/vb2themax/Tip/19316工作 - 我得到了错误的值回。谢谢你的建议。
没有证据表明它有效。我调整了代码的一些声明和肤浅的结构,以便在Visual Studio Express 2010 Visual Basic中成功构建它。然后逐步介绍Visual Studio Express 2010 Visual Basic调试器中的代码,代码很难遵循:变量名称不明显,没有评论为什么它正在做它正在做的事情。从我所了解的情况来看,它似乎不应该那样做基础转换。
它有一个链接到这(不检查,如果它使用递归):http://www.devx.com/vb2themax/Tip/19316 – assylias 2012-03-16 11:39:20
+1 @assylias感谢它看起来很有希望,现在检查它... – therobyouknow 2012-03-16 11:47:33
是的,看起来无递归:)我已经看了一遍,这不是最可读的代码和VB使用函数名称作为返回值可能会误导,但是,似乎是递归免费。所以现在我将把它集成到我的Visual Studio 2010 Express Visual Basic项目中并进行测试。我会回来报告,如果确定@assylias,如果你然后提供这个答案我应该能够接受它,并upvote它。 – therobyouknow 2012-03-16 12:06:33