2

I want to convert string of array to byte array and vice-versa

Eg.

string[] strArr= new string[]{"1","2","3"};
Byte[] byteArr= strArr.Select(byte.Parse).ToArray()

Now want to convert it back again to

string [] originalArr= ??? from Byte[]

I tried

strArr.Select(innerArray => Encoding.UTF8.GetString(innerArray)).ToList();

but not working

Pikoh
  • 7,582
  • 28
  • 53
PratikD
  • 65
  • 1
  • 1
  • 7
  • What do you mean by `not working` ? – Chetan Apr 24 '17 at 14:14
  • 1
    Wow wow Mr. Faktorovich, it's not duplicating the question that you are referring. – Andrei Apr 24 '17 at 14:17
  • 3
    It's not really a duplicate - OP wants to know how to convert an array of strings to an array of bytes & then convert the array of bytes back to a matching array of strings. – PaulF Apr 24 '17 at 14:18
  • Getting error at this line byte[] bytes = strings.Select(byte.Parse).ToArray(); – PratikD Apr 24 '17 at 14:29
  • Input string was not in correct format if my string is like {"ProductCode":"PP211766","IsItem":"True","IsBPA":"True"} – PratikD Apr 24 '17 at 14:30
  • Can the strings in your question also be Characters ? ore more than one number? If it is the answer from @Andrei is not right. If you use a number bigger than 255 it will trow an `argument out of range exception`. And if characters in the string array it will throw an `Input string was not in correct format` – Timon Post Apr 24 '17 at 14:30
  • If my string is like this "{\"ProductCode\":\"PP202920\",\"IsItem\":\"True\",\"IsBPA\":\"False\"}" – PratikD Apr 24 '17 at 14:32
  • @Pratik9975 it looks more like a JSON for me. Are you trying to deserialize JSON to an object? – Andrei Apr 24 '17 at 14:39
  • I am in situation where i want to send NServiceBus message with data string array and this carries around 50000 elements in array but NServiceBus not allow to send message size greater that 4MB so i need to convert it into byte array as per nservicebus documentation. My array is like string[] arr= new string[]{"{\"ProductCode\":\"PP202920\",\"IsItem\":\"True\",\"IsBPA\"‌​:\"False\"}","{\"ProductCode\":\"PP202920\",\"IsItem\":\"True\",\"IsBPA\"‌​:\"False\"}","PP00001","123456"} – PratikD Apr 25 '17 at 04:22

1 Answers1

3

Simply:

string[] strings = new string[] { "1","2","3" };
byte[] bytes = strings.Select(byte.Parse).ToArray();
strings = bytes.Select(byteValue => byteValue.ToString()).ToArray();

Warning: byte.Parse will throw runtime exception if string can't be converted to byte e.g. it's not a number of it's >255. Additional checks may be needed for correct execution. Check out byte.TryParse documentation.


This is just one of the ways. You may also find Convert class very useful. It has many static methods to convert values to different types, including Convert.ToByte(...) or Convert.ToString(...). Please see MSDN for more details.

Andrei
  • 42,814
  • 35
  • 154
  • 218