| Author: Steve Howard 30 Oct 2004 | Member Level: Bronze Points : 0 |
I modified these functions to correct method parameter and return types and also streamlined them a bit.
Public Function ToInteger(ByVal x As String) As Integer Dim temp As Integer Dim ch As Char Dim multiply As Integer = 1 Dim subtract As Integer = 1 Dim len As Integer
For Each ch In x For len = 1 To x.Length - subtract multiply *= 2 Next multiply *= Integer.Parse(ch.ToString) temp += multiply subtract += 1 multiply = 1 Next
Return temp End Function
Public Function ToBinary(ByVal x As Integer) As String Dim temp As String = ""
Do While x > 0 If x Mod 2 = 0 Then temp = "0" + temp Else temp = "1" + temp End If x = x \ 2 Loop Return temp End Function
Hope they are ok now!
Cheers, Steve
|
| Author: J Ladd 12 Nov 2004 | Member Level: Bronze Points : 0 |
I wanted the leading zeros in an 8-bit representaion. I also used a string builder which is more efficient that using just a string.
Imports System.Text
Public Function ToBinary(ByVal x As Integer) As String
Dim Bin As StringBuilder = New StringBuilder
Do While x > 0 If x Mod 2 = 0 Then Bin.Insert(0, "0")
Else Bin.Insert(0, "1")
End If x = x \ 2 Loop
Bin.Insert(0, "0", 8 - Bin.Length) Return Bin.ToString
End Function
|
| Author: Steve Howard 13 Nov 2004 | Member Level: Bronze Points : 0 |
I just discovered the built in conversion function. The function could also be written:
Public Function ToBinary(Int as Integer) As String Return Convert.ToString(Int, 2) End Function
Where Int can be any integer value 16, 32 or 64 bit. The function's 2nd parameter designates the numeric base (radix) to be returned eg. base 2, 8 or 16.
Hope this helps.
Cheers, Steve
|
| Author: Steve Howard 14 Nov 2004 | Member Level: Bronze Points : 0 |
And finally, to convert a binary string to an integer:
Public Function ToInteger(ByVal s as String) As Integer Return Convert.ToInt32(s, 2) End Function
Variations on this ToInt function exist for other integer types as well. You may now question the need for creating your own functions, but you could wrap the various conversions in your own class along with formatting features I guess.
Cheers, Steve
|