2

我有一个字符串:

LogoDataStr = "ABC0000"

我想转换为 ASCII 字节,结果应该是:

LogoDataBy[0] = 0x41;
LogoDataBy[1] = 0x42;
LogoDataBy[2] = 0x43;
LogoDataBy[3] = 0x30;
LogoDataBy[4] = 0x30;
LogoDataBy[5] = 0x30;
LogoDataBy[6] = 0x30;

我试过用这种方式:

byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes(LogoDataStr);

但我得到的结果是这样的:

LogoDataBy[0] = 0x41;
LogoDataBy[1] = 0x42;
LogoDataBy[2] = 0x43;
LogoDataBy[3] = 0x00;
LogoDataBy[4] = 0x00;
LogoDataBy[5] = 0x00;
LogoDataBy[6] = 0x00;

我的编码有什么问题吗?

4

3 回答 3

16

这段代码

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

产生预期的输出

在此处输入图像描述

在读取 ASCII 字节之前,请仔细检查您的代码和字符串的值。

于 2012-09-19T08:01:33.500 回答
3

只是扔:

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

Into LinqPAD 给出(十进制)的输出:

字节[](7 项)
65
66
67
48
48
48
48

所以我不确定你是如何得到 0x00 的......

于 2012-09-19T08:06:09.377 回答
0
    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;
        }
    }

我就是这样做的。只要 Encoding.ASCII.GetBytes() 会返回错误值。

于 2012-09-19T08:23:48.573 回答