-1

How can I convert the string "0100" to a byte array {0,1,0,0} without using Convert.ToByte() on each element? The string may only contain characters 0 thru 9.

JP_99
  • 125
  • 8
  • Following links should help 1) https://stackoverflow.com/questions/16072709/converting-string-to-byte-array-in-c-sharp 2) https://stackoverflow.com/questions/30545162/how-to-convert-string-to-byte-array?noredirect=1&lq=1 3) https://stackoverflow.com/questions/6254003/string-values-to-byte-array-without-converting 4) http://rextester.com/discussion/HHSUSW47299/Converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte- – Atur Apr 03 '18 at 16:48
  • Are you assuming that the characters in your string will always be digits in the range 0-9, or always in an 8-bit character set? – Jim Mischel Apr 03 '18 at 16:48
  • @atur I said not with Encoding, example A becomes 65. Just 0 becomes 0 in byte. – JP_99 Apr 03 '18 at 16:50
  • @JimMischel Yes, sorry I will edit this. – JP_99 Apr 03 '18 at 16:51
  • @JP_99 : Couple of links are without encoding. Moreover, see all answer not just the accepted ones – Atur Apr 03 '18 at 16:51
  • @JP_99 : Also it seems you just want to split the string by char (0-9) and aggregate the result in byte array. Eser's answer looks enough to perform that function. – Atur Apr 03 '18 at 17:11
  • @atur all answers in the duplicate link convert characters to their ASCII values, like '0'->48, '1'->49. Below code returns 1 for '1'. So it is not only *enough*, it is correct. – Eser Apr 03 '18 at 17:31
  • @Eser Yes, I checked them all. Only your answer fulfills OP's doubt +1. :) – Atur Apr 03 '18 at 17:34

1 Answers1

5

With linq

var bytes = "0100".Select(x => (byte)(x - '0')).ToArray();
Eser
  • 12,346
  • 1
  • 22
  • 32