簡體   English   中英

將純文本字符串轉換為十六進制樣式的字節數組?

[英]Converting a String with plain text to byte array in hex style?

我可以找到很多關於如何將十六進制格式的字符串轉換為十六進制字節數組的答案,但我想知道如何將帶有文本的字符串轉換為字節數組。

為了給你一個想法,這里是使用十六進制格式將文本轉換為字節數組的代碼:

FileStream fs = File.OpenRead(filePath);
byte[] fileInBytes;
using (BinaryReader br = new BinaryReader(fs))
{
    List<byte> bytesList = new List<byte>();
    while (fs.Position < fs.Length)
    {
        bytesList.Add(byte.Parse(Encoding.ASCII.GetString(br.ReadBytes(2)), 
            NumberStyles.HexNumber));
    }
    fileInBytes = bytesList.ToArray();
}
return fileInBytes;

如何使用String實現此目的?

public static byte[] getBytesFromString(String str)
{
    //What now?
}

基本上,如果我輸入一個包含16個字符的字符串,我想返回一個8字節的字節數組。

我不確定你會得到多少字節,但見下文。

public static byte[] getBytesFromString(String str)
{
   return Encoding.ASCII.GetBytes(str)
}

如果我了解你的代碼應該是什么樣子:

public byte [] getBytesFromString2(string str)

{

        IList<byte> retValue = null;

        if (!string.IsNullOrEmpty(str) && str.Length == 16)
        {
            MemoryStream s_stream;

            using (s_stream = new MemoryStream(Encoding.ASCII.GetBytes(str)))
            {
                using (var br = new BinaryReader(s_stream))
                {
                    retValue = new List<byte>();

                    while (s_stream.Position < s_stream.Length)
                    {
                        retValue.Add(byte.Parse(Encoding.ASCII.GetString(br.ReadBytes(2)),
                            System.Globalization.NumberStyles.HexNumber));
                    }
                }
            }
        }

        return retValue.ToArray();
    }

暫無
暫無

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

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