0

assume i got the following byte[]

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72

with bitconverter BitConverter.ToString i can convert it to

0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72

how do i convert it back from string to byte[] to get

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72

ascii encoding and other methods always getting me the equivalent bytes to the string but what i really need is the string to be byte[] as it is, i know if i did a reversing operation (using getbytes then tostring) ill end up with the same string but what i care about is while at getbytes to get the exact bytes

as i said

to put

0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72

AS string

and get

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72

As byte[]

thanks in advance

terrybozzio
  • 4,424
  • 1
  • 19
  • 25
Andrew
  • 218
  • 4
  • 18
  • possible duplicate of [How do you convert Byte Array to Hexadecimal String, and vice versa?](http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa) – Jon Skeet Jul 27 '13 at 16:53
  • did you check http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa?rq=1 – steve cook Jul 27 '13 at 16:54

3 Answers3

4

You need this

byte[] bytes = str.Split('-').Select(s => Convert.ToByte(s, 16)).ToArray();
Ehsan
  • 31,833
  • 6
  • 56
  • 65
3

You can use SoapHexBinary class in System.Runtime.Remoting.Metadata.W3cXsd2001 namespace

string s = "0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72";
byte[] buf  = SoapHexBinary.Parse(s.Replace("-"," ")).Value;
I4V
  • 34,891
  • 6
  • 67
  • 79
2

Remenber that BitConverter.ToString returns an equivalent hexadecimal string representation,so if you decide to stick with it converting back as follow:

string temp = BitConverter.ToString(buf);//buf is your array.
byte[] newbuf = temp.Split('-').Select(s => Convert.ToByte(s,16)).ToArray();

But the safest way to convert bytes to string and back is base64:

string str = Convert.ToBase64String(buf);
byte[] result = Convert.FromBase64String(str);
terrybozzio
  • 4,424
  • 1
  • 19
  • 25
  • http://stackoverflow.com/questions/1134671/c-how-can-i-safely-convert-a-byte-array-into-a-string-and-back – terrybozzio Jul 27 '13 at 18:19
  • It is about `not to get "invalid" unicode sequences (encoding.GetString(byteArray) for ex.,)`. What can be the problem when you only use the chars `0-9` and `A-F` ? – I4V Jul 27 '13 at 18:53