jayeldee said:
Dim sBase As String = "1234ABCD"
Dim bBase() As Byte
Dim sHex As String = String.Empty
Dim sHexByte As String
bBase = System.Text.ASCIIEncoding.ASCII.GetBytes(sBase)
For i As Integer = 0 To bBase.Length - 1
sHexByte = bBase(i).ToString("x")
If sHexByte.Length = 0 Then
sHexByte = "0" & sHexByte
End If
sHex &= sHexByte
Next
Console.WriteLine(sHex)
Console.ReadLine()
Just a few suggestions, hope you don't mind...
You don't need to keep track of the byte index (the For i As
Integer... loop). Instead you may want to use a For Each loop -- just
a question of preference, though, but the loop may become more
"readable":
For Each B As Byte In Sytem.Text.Encoding. _
ASCII.GetBytes(Base64Text)
...
Next
Also, you'll be glad to know that the ToString("x") method of the
integer data types (Byte, Integer, Long, UInteger, etc) allows a
"length" parameter, so you don't have to manually padd the returned
string:
For Each B As Byte In Sytem.Text.Encoding. _
ASCII.GetBytes(Base64Text)
'HexChar will be zero-padded up to two digits
Dim HexChar As String = B.ToString("x2")
...
Next
Finally, just remember that base64 encoded strings are *usually* used
to encode a large amount of data. Concatenating strings in a loop
using the "&" operator is not a real problem if the number of
iterations is small -- but, how many is "small"? Don't ask me.
Personally, I'll resort to a StringBuilder whenever I see a loop. Of
course, there's no rule in stone, here. But since we may consider that
the typical content of a base64 encoded string can be quite large, the
use of a StringBuilder may be advised:
Dim S As New System.Text.StringBuilder
For Each B As Byte In Sytem.Text.Encoding. _
ASCII.GetBytes(Base64Text)
S.Append(B.ToString("x2"))
Next
HexText = S.ToString
Just for the fun of it (and if the OP doesn't mind writing VB code
that threads on the limits of readability), we could also have:
Public Function CharToHex(Value As Char) As String
Return Convert.ToByte(Value).ToString("x2")
End Function
'...
HexText = String.Join(Nothing, _
System.Array.ConvertAll(Of Char, String)( _
Base64Text.ToCharArray, AddressOf CharToHex))
)
Regards,
Branco.