0

Let's say we have a byte array called buff. The first three way works just fine but the 4th way throws and exception. The only difference from the third way is that u give it the offset and length. I am not sure why the fourth way doesn't work.

            // First way - works
            string converted = Encoding.UTF8.GetString(buff, 0, buff.Length);
            Console.WriteLine("converted = " + converted);
            // Second way - works
            var str = System.Text.Encoding.Default.GetString(buff);
            Console.WriteLine("str = " + str);
            // Third way - works
            string ASCII = Encoding.ASCII.GetString(buff, 0, buff.Length);
            Console.WriteLine("ASCII = " + ASCII);
            // Fourth way - doesn't work
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string byteCountString = asciiEncoding.GetString(buff);
user9864738
  • 17
  • 1
  • 7
  • 2
    It will help your readers immensely if you show them the exception being thrown. For more tips on asking effective questions see [ask] and [mcve] – Frank Boyne Jun 05 '18 at 03:59
  • What is the exception? – Yeldar Kurmangaliyev Jun 05 '18 at 03:59
  • Code works for me. I think you are misreading the error, since `GetString()` does not have any "input string" (it has an input `byte[]`). The error may be on a different line or within a different function, and you have them confused. Maybe post the exception's stack trace. – John Wu Jun 05 '18 at 04:08
  • asciiEncoding doesn't contain any encoding so it will fail. You just call the constructor but didn't add any properties. The other 3 methods in order have following encoding 1) UTF8 2) Default 3) ASCII – jdweng Jun 05 '18 at 04:25
  • @jdweng https://stackoverflow.com/a/20880556/505088 – David Heffernan Jun 05 '18 at 05:15
  • What on earth are you *trying to do*? In general, you cannot expect to take a byte array and decode it using *multiple* encodings and get any sensible results. You need to *know* the encoding used for the byte array (or attempt to apply heuristics to determine the encoding). – Damien_The_Unbeliever Jun 05 '18 at 07:18
  • The error is in the title: “Message: Input string was not in a correct format”. @jdweng ah, so I have to define the encoding. @ Damien_The_Unbeliever I tried 3 other decoding just to see which works...was unclear why the 4th one failed. – user9864738 Jun 05 '18 at 12:22
  • 1
    The first three might work but only one or none are correct. What is the encoding used to create the bytes from text? – Tom Blodget Jun 05 '18 at 16:36
  • 1
    I personally don't see why the fourth variant fails. What is in the byte array? – David Heffernan Jun 05 '18 at 23:19

0 Answers0