Opposite/reverse of BitConverter.ToString()

D

Daniel Moth

Hi

BitConverter.ToString produces a string given a byte array. Is there method
that takes that string to produce a byte array?

I know it is only 4 lines of code to get the result but if there is a
built-in function I'd prefer to use that... Anybody found one?

Cheers
Daniel
 
A

Alex Yakhnin [MVP]

System.Text.ASCIIEncoding.ASCII.GetBytes

or approriate encoder should get you that.
 
D

Daniel Moth

Hmm...

BitConverter.ToString
returns the hex values of each byte (separated by hyphens)

AnyEncoding.GetBytes()
will translate the chars from the string into bytes (rather than read
each hex value into a byte ignoring the hyphens)

Am I missing some overload?

The 4 lines (without word wrap) that do the trick are (in VB):
Dim b((s.Length \ 2) - 1) As Byte
For i As Int32 = 0 To b.GetUpperBound(0)
b(i) = Byte.Parse(s.Substring(i * 2, 2),
Globalization.NumberStyles.HexNumber)
Next i

Assuming the string was created with:
s = BitConverter.ToString(b).Replace("-", String.Empty)


But as I said, if there is a framework equivalent I'd rather use that (and
hence preserve the hyphens)...

Cheers
Daniel
 
A

Alex Yakhnin [MVP]

Sorry, I misunderstood your question. I don't think there's anything else in
the CF that would do what you want. So you're better off with your 4 lines
:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top