|
原帖由 泓() 于 2009-9-26 19:19 发表
修正了(优化后的)一个bug
请刘版 查收
收到 -ldy
- '论坛ID:泓() 结果正确,+2 但处理负数效率太低。N10toCX 多余且绕弯
- '一个清如水,一个乱如泥,老兄在玩冰火两重天?
- Function N10toCX(ByVal L As Long, ByVal N As Integer) As String
- '正十进制 转 N进制
- Dim v As Long
- Const Jzs As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- If L = 0 Then N10toCX = 0: Exit Function
- Do While L > 0
- v = L - Int(L / N) * N + 1
- N10toCX = Mid$(Jzs, v, 1) & N10toCX
- L = Int(L / N)
- Loop
- End Function
- Function N2ChrX(ByVal L As Long, ByVal N As Integer) As String' 乱,但居然对了,太神奇了
- '作用:将Long值转换为 N 进制所表示的字符串
- '参数说明 L 要转换的值, N (2-36) 将要使用的进制数
- Dim i As Long, j As Long, S As String, t As String, Ls As Long, Ss As String
- Dim F As String, Z As String, b As Long, c As Long, d As Long, H() As Variant
- Const Jzs As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- If Not (N >= 2 And N <= 36) Then Exit Function
- If N = 10 Then N2ChrX = CStr(L): Exit Function '若十进制 没必要进一步转化
- If L > -1 Then
- N2ChrX = N10toCX(L, N)
- Exit Function '正十进制转 N进制后 直接退出
- End If
- '------以下代码针对 负数 转化------
- S = N10toCX(2147483647, N) '转化Long最大值2147483647 N进制中的值
- Ls = Len(S)
- For i = Ls To 1 Step -1
- j = j + 1: t = Mid$(S, i, 1)
- If InStr(Jzs, t) < N Then Ss = Left(S, Ls - j) & _
- Mid$(Jzs, InStr(Jzs, t) + 1, 1) & Application.Rept(0, j - 1): Exit For
- Next
- If Ss = Empty Then Ss = 1 & Application.Rept(0, Ls)
- F = Ss '+1 计算Long最小值 -2147483648 N进制值
- L = 2147483647 + L + 1 'L =:原始值L与 最小值-2147483648 的相差值(10进制中的相差)
- Z = N10toCX(L, N) '十进制中的相差值转为 N进制值
- Z = Application.Rept(0, Len(F) - Len(Z)) & Z
- '以下代码是N进制的加法运算: N进制相差值 + N进制最小值 = 负十进制L转为 N进制值
- ReDim H(0 To Len(F)) As Variant
- For i = Len(F) To 1 Step -1
- b = InStr(Jzs, Mid$(Z, i, 1)) - 1
- c = InStr(Jzs, Mid$(F, i, 1)) - 1
- d = b + c + H(i)
- If d < N Then
- H(i) = Mid$(Jzs, d + 1, 1)
- Else
- H(i - 1) = d \ N
- H(i) = Mid$(Jzs, d Mod N + 1, 1)
- End If
- Next
- S = Empty
- For i = 0 To UBound(H)
- S = S & H(i)
- Next
- N2ChrX = S
- End Function
- Function ChrX2N(ByVal S As String, ByVal N As Integer) As Long '这个思路清晰,正解,上面的咋那么乱?
- '作用:字符串值转换为 N 进制所表示的字符串
- '参数说明 S 要转换的N进制字符串, N (2-36) 对S变量进制数的说明
- Dim i As Long, v As Double, Ls As Long, im As Long
- Const Jzs As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- S = UCase(S)
- If Not (N >= 2 And N <= 36) Then Exit Function
- If N = 10 Then ChrX2N = CLng(S): Exit Function
- Ls = Len(S)
- For i = Ls To 1 Step -1
- im = InStr(Jzs, Mid$(S, i, 1))
- If im = 0 Then Exit Function
- v = v + (im - 1) * N ^ (Ls - i)
- Next
- If v > 2147483647 Then v = v - 2147483648# * 2
- ChrX2N = v
- End Function
复制代码
[ 本帖最后由 ldy 于 2009-10-21 17:38 编辑 ] |
评分
-
1
查看全部评分
-
|