为什么负数(长整型)在->二进制->十进制转换后变成正数啦?

wdthkyou 2006-12-05 09:15:09
进制转换我不太明白,各位帮我指点一下,按照如下代码运行就出现上述问题,如何在进制转换后得到正确的值啦?
Private Sub Command1_Click()
Dim f As Long, s As String, d As Long
f = -1234567
s = DecimalToBinary(f, 20)
d = BinaryToDecimal(s)
f = 0
End Sub
Private Function BinaryToDecimal(BinaryValue As String) As Long
Dim idx As Integer
Dim tmp As String
Dim result As Long
Dim digits As Integer
digits = Len(BinaryValue)
For idx = digits To 1 Step -1
tmp = Mid(BinaryValue, idx, 1)
If tmp = "1" Then result = result + 2 ^ (digits - idx)
Next
BinaryToDecimal = result
End Function
Private Function DecimalToBinary(DecimalValue As Long, MinimumDigits As Integer) As String

Dim result As String
Dim ExtraDigitsNeeded As Integer

Do
result = CStr(DecimalValue Mod 2) & result
DecimalValue = DecimalValue \ 2
Loop While DecimalValue > 0

' 如果转换出来的二进制长度低于给定的最小值则添0

ExtraDigitsNeeded = MinimumDigits - Len(result)
If ExtraDigitsNeeded > 0 Then
result = String(ExtraDigitsNeeded, "0") & result
End If

DecimalToBinary = result

End Function
...全文
244 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wdthkyou 2006-12-05
  • 打赏
  • 举报
回复
怎样写才对正负长整型的进制转换都有效啦?
of123 2006-12-05
  • 打赏
  • 举报
回复
你所用的函数是用于无符号数的。

7,763

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧