Opposite/reverse of BitConverter.ToString()

  • Thread starter Thread starter Daniel Moth
  • Start date Start date
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
 
System.Text.ASCIIEncoding.ASCII.GetBytes

or approriate encoder should get you that.
 
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
 
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
:)
 
Back
Top