C# Convert a string to ASCII bytes

前端 未结 3 791
旧时难觅i
旧时难觅i 2021-01-20 05:30

I have a string:

LogoDataStr = \"ABC0000\"

I want to convert to ASCII bytes and the result should be:

LogoDataBy[0] = 0x41;         


        
相关标签:
3条回答
  • 2021-01-20 05:39

    Just throwing:

    Encoding.ASCII.GetBytes("ABC0000").Dump();
    

    Into LinqPAD gives an output of (decimal):

    Byte[] (7 items)
    65
    66
    67
    48
    48
    48
    48

    So I'm not sure how you're getting 0x00...

    0 讨论(0)
  • 2021-01-20 05:49

    This code

    class Program
    {
        static void Main(string[] args)
        {
            byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes("ABC000");
        }        
    }
    

    produces expected output

    enter image description here

    Double check your code and the value of the string before you read ASCII bytes.

    0 讨论(0)
  • 2021-01-20 06:03
        class CustomAscii
        {
            private static Dictionary<char, byte> dictionary;
    
            static CustomAscii()
            {
                byte numcounter = 0x30;
                byte charcounter = 0x41;
                byte ucharcounter = 0x61;
                string numbers = "0123456789";
                string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                string uchars = "abcdefghijklmnopqrstuvwxyz";
                dictionary = new Dictionary<char, byte>();
                foreach (char c in numbers)
                {
                    dictionary.Add(c, numcounter++);
                }
                foreach (char c in chars)
                {
                    dictionary.Add(c, charcounter++);
                }
                foreach (char c in uchars)
                {
                    dictionary.Add(c, ucharcounter++);
                }
            }
    
            public static byte[] getCustomBytes(string t)
            {
                int iter = 0;
                byte[] b = new byte[t.Length];
                foreach (char c in t)
                {
                    b[iter] = dictionary[c];
                    //DEBUG: Console.WriteLine(b[iter++].ToString());
                }
    
                return b;
            }
        }
    

    This is how i would do it. JUST IF Encoding.ASCII.GetBytes() would return wrong values.

    0 讨论(0)
提交回复
热议问题