簡體   English   中英

C#將字符串轉換為ASCII字節

[英]C# Convert a string to ASCII bytes

我有一個字符串:

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;

我的編碼有問題嗎?

這段代碼

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

產生預期的產出

在此處輸入圖片說明

在讀取ASCII字節之前,請仔細檢查您的代碼和字符串的值。

只是拋出:

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

到LinqPAD中,輸出為(十進制):

字節[](7個項目)
65歲
66
67
48
48
48
48

所以我不確定你怎么得到0x00 ...

    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()會返回錯誤的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM