进制数换算
2024-06-04 08:25:23 阅读次数:21
进制
'十进制数转换成十六进制数
Public Shared Function DecToHex(ByVal value As Integer) As String
Return BinToHex(DecToBin(value))
End Function
'二进制数转换成十进制数
Public Shared Function BinToDec(ByVal value As String) As Integer
Dim i As Integer
Dim returnValue As Integer = 0
For i = value.Length - 1 To 0 Step -1
returnValue += Val(value.Chars(value.Length - 1 - i)) * (2 ^ i)
Next Return returnValue
End Function '任意二进制数转换成十六进制数
Public Shared Function BinToHex(ByVal value As String) As String
If value.Length Mod 4 <> 0 Then
value = value.PadLeft(4 * (value.Length / 4 + 1), "0"c)
End If Dim i As Integer
Dim returnString As String = ""
Dim tempString As String
For i = 0 To value.Length / 4 - 1
tempString = value.Chars(4 * i) + value.Chars(4 * i + 1) _
+ value.Chars(4 * i + 2) + value.Chars(4 * i + 3) returnString += GetHexChar(tempString)
Next Return returnString
End Function '特殊情况:4位二进制数转换成十六进制数
Public Shared Function GetHexChar(ByVal value As String) As String
Dim tempValue As Integer
tempValue = BinToDec(value) If tempValue < 10 Then
Return CStr(tempValue)
Else
Select Case tempValue - 10
Case 0
Return "A"
Case 1
Return "B"
Case 2
Return "C"
Case 3
Return "D"
Case 4
Return "E"
Case 5
Return "F"
End Select
End If
End Function '仅限非负整数
'十进制数转换成二进制数
Public Shared Function DecToBin(ByVal value As Integer) As String
If value = 0 Then Return "0" Dim tempValue As Integer = value
Dim tempString As String = "" Dim modValue As Integer
Do
tempString += CStr(tempValue Mod 2)
tempValue = tempValue / 2
Loop While (tempValue <> 0) Dim i As Integer
Dim returnChars As Char() = tempString.ToCharArray()
Dim returnString As String = ""
For i = tempString.Length - 1 To 0 Step -1
returnString += returnChars(i)
Next Return returnString
End Function '十六进制数转换成十进制数
Public Shared Function HexToDec(ByVal value As String) As Integer
Dim i As Integer
Dim returnValue As Integer = 0
For i = value.Length - 1 To 0 Step -1
Dim num As Integer = 0
Select Case value.Chars(value.Length - 1 - i)
Case "0"c To "9"c
num = Val(value.Chars(i))
Case "A"c
num = 10
Case "B"c
num = 11
Case "C"c
num = 12
Case "D"c
num = 13
Case "E"c
num = 14
Case "F"c
num = 15
End Select returnValue += num * (16 ^ i)
Next Return returnValue
End Function
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/u_11954054/9737529,作者:A零零八,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。
上一篇:设计模式之解释器模式(Interpreter Pattern)
下一篇:IPv6路由综合运用