2013年10月28日 星期一

特殊資料類型轉換函式

參考引用來源
--
'浮點數轉二進位  
Private Function DecimalToBinary(ByVal DecValue As Integer, Optional ByVal Num As Integer = 16) As String
      Dim sValue As String = Convert.ToString(DecValue, 2)
      Return String.Format("{0:x" & (Num - sValue.Length).ToString & "}", 0) & sValue
  End Function

  Public Function BinaryToInteger(ByVal sData As String) As Integer
      Dim I As Int16
      Dim bTemp As Integer

      bTemp = 0
      For I = sData.Length - 1 To 0 Step -1
          bTemp = bTemp + Val(sData.Substring(I, 1)) * 2 ^ (sData.Length - 1 - I)
      Next
      Return bTemp
  End Function

'Byte轉二進位
Public Function ByteToBinary(ByVal bData As Byte) As String
      Return Strings.Right("00000000" & BinaryRecursive(bData), 8)
  End Function

  Public Function BinaryRecursive(ByVal bData As Byte) As String
      If bData > 1 Then
          Return BinaryRecursive(bData >> 1) & IIf((bData And 1) = 1, "1", "0")
      Else
          Return "1"
      End If
  End Function

  '二進位轉Byte
  Public Function BinaryToByte(ByVal sData As String) As Byte
      Dim I As Int16
      Dim bTemp As Byte

      bTemp = 0
      For I = sData.Length - 1 To 0 Step -1
          bTemp = bTemp + Val(sData.Substring(I, 1)) * 2 ^ (sData.Length - 1 - I)
      Next
      Return bTemp 
  End Function

沒有留言:

張貼留言