iThomas
iThomas

Reputation: 15

VB .NET Convert string to array of bytes without converting the characters

I'm trying to split a string of 32 numerical characters into a 16 length Array of Byte and each value has to stay numerical

from "70033023311330000000004195081460" to array {&H_70, &H_03, &H_30, &H_23, ..}

I've tried multiple stuff but each time either it's the conversion that's wrong or I can't find the appropriate combination of functions to implement it.

'it splits but per 1 character only instead of two
str.Select(Function(n) Convert.ToByte(n, 10)).ToArray

'I also tried looping but then the leading zero disappears and the output is a string converted to HEX which is also not what I want.
Function ConvertStringToHexBinary(str As String) As Byte()
        Dim arr(15) As Byte
        Dim k = 0
        For i As Integer = 0 To str.Length - 1
            arr(k) = str(i) & str(i + 1)
            k += 1
            i += 1
        Next
        Return arr
    End Function

Anyone got any suggestion what to do?

Upvotes: 0

Views: 604

Answers (2)

Caius Jard
Caius Jard

Reputation: 74595

G3nt_M3caj's use of LINQ might be.. er.. appealing to the LINQ lovers but it's horrifically inefficient. LINQ is a hammer; not everything is a nail.

This one is about 3 times faster than the LINQ version:

Dim str As String = "70033023311330000000004195081460"
Dim byt(str.Length/2) as Byte
For i = 0 to str.Length - 1 Step 2
  byt(i/2) = Convert.ToByte(str.Substring(i, 2))
Next i

And this one, which does it all with math and doesn't do any new stringing at all is just under 3 times faster than the above (making it around 9 times faster than the LINQ version):

Dim str As String = "70033023311330000000004195081460"
Dim byt(str.Length / 2) As Byte
For i = 0 To str.Length - 1
    If i Mod 2 = 0 Then
        byt(i / 2) = (Convert.ToByte(str(i)) - &H30) * &HA
    Else
        byt(i / 2) += Convert.ToByte(str(i)) - &H30
    End If
Next i

Of the two, I prefer the stringy version because it's easier to read and work out what's going on - another advantage loops approaches often have over a LINQ approach

Upvotes: 1

G3nt_M3caj
G3nt_M3caj

Reputation: 2685

Do you need something like this?

 Dim str As String = "70033023311330000000004195081460"
 Dim mBytes() As Byte = str.
        Select(Function(x, n) New With {x, n}).
        GroupBy(Function(x) x.n \ 2, Function(x) x.x).
        Select(Function(y) Convert.ToByte(New String(y.ToArray()), 10)).ToArray

Upvotes: 0

Related Questions