Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 332
  • Last Modified:

vb.net shorten code

hello there,
this is working perfectly fine but I would like to know if its possible to get the same results with a shorter code..

        Dim enc2 As New System.Text.UTF8Encoding()
        Dim enc3 As String = enc2.GetString(bBuffer)
        Dim abData() As Byte
        abData = System.Text.Encoding.Default.GetBytes(enc3)
        Dim i As Long
        enc3 = ""
        For i = 0 To UBound(abData)
            If Hex(abData(i)).Length = 1 Then
                enc3 += "0" & Hex(abData(i)) & " "
            Else
                enc3 += Hex(abData(i)) & " "
            End If
        Next

Open in new window

0
XK8ER
Asked:
XK8ER
2 Solutions
 
Element1910Commented:
You did a pretty good job of getting it pretty much down to as little code as possible. The only thing I notice is that you can get rid of Dim i as Long and combine it into the for loop, like so:
Dim enc2 As New System.Text.UTF8Encoding()
Dim enc3 As String = enc2.GetString(bBuffer)
Dim abData As Byte() = Nothing
abData = System.Text.Encoding.[Default].GetBytes(enc3)
enc3 = ""
For i As Long = 0 To Information.UBound(abData)
	If Hex(abData(i)).Length = 1 Then
		enc3 += "0" & Hex(abData(i)) & " "
	Else
		enc3 += Hex(abData(i)) & " "
	End If
Next

Open in new window

0
 
Robert SchuttSoftware EngineerCommented:
Only half tested but give this a go.

The bit inside the for-next can be done with:
enc3 += abData(i).ToString("X2") & " "

Open in new window

But for the whole thing in one try this:
enc3 = BitConverter.ToString(abData)

Open in new window

You could replace the dashes with spaces of course. Or even use that on bBuffer but I'm not sure what you're doing with the UTF conversion...
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now