簡體   English   中英

如何將大的十六進制字符串轉換為字節數組?

[英]How to convert a large hexadecimal string to a byte array?

嗨,我需要使用文件處理,為此我使用了一種將十六進制字符串轉換為字節數組的方法。

public static byte[] StringToByteArray(string hex)
{
   return Enumerable.Range(0, hex.Length)
                    .Where(x => x % 2 == 0)
                    .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                    .ToArray();
}

我的問題是,當我給這個函數提供一個小的十六進制字符串作為參數時,它會產生正確的輸出,但是當我使用一個大的十六進制字符串作為參數輸出時,並不是預期的。

為了您的清楚了解 -

我使用了一個從值 [26246026] 的字節數組轉換的十六進制字符串,當我將該十六進制字符串轉換為字節數組時,它應該返回一個字節值 [26246026] - 但它只返回部分字節即。 262144]。

我無法從十六進制字符串中獲得確切的字節值,我該如何獲得? 請有人幫助我獲得預期的輸出。

我的該方法的輸入字符串包含這個十六進制字符串,它是一個 25mb 大小的文件 - 它應該返回 [26246026] 的字節值---但它只返回 [262144] 的字節值。

當我使用小十六進制字符串(最小文件大小)時,它工作正常,但是當我處理大文件時,我無法獲得原始文件字節。 請建議我該怎么做。

我的輸入參數字符串內容如下評論中所問。

它的總長度為 524288 個字符。

看起來像這樣。

3026b2758e66cf11a6d900aa0062ce6c301600000000000008000000010240a4d0d207e3d21197f000a0c95ea850cc0000000000000004001c00530066004f0072006900670069006e0061006c00460050005300000003000400b49204001c0057004d004600530044004b00560065007200730069006f006e00000000001e00310031002e0030002e0036003000300031002e00370030003000300000001a0057004d004600530044004b004e006500650064006500640000000000160030002e0030002e0030002e00300030003000300000000c0049007300560042005200000002000400000000003326b2758e66cf11a6 ................................................. ………………………………………………………………………………………………………………………………………………………… ....................................... d900aa0062ce6c54010000000000001e0000003a00da000000570dcb8b495848cea4609eca906bc24db442394f0ddac5eb0604fb99820bcc30ff0f1736eefd74cd4317a21a369e208c580dbb02f90e888f0a35901e08439ec6087c61d241bc3c476c24d311291a678596a98792a9000b68adf213906e0f00097c8d989e517ee532fcd6cb70e520ec9dd4fad8a1a37668bbd678bea11c1fcf2d187c4c4c6c09c3c2c53d3e64016cfebc34eace85d45a4c08cd78d05d3934e05b72ec1 94304848165a8c1a585c78423

    /// <summary>
    /// Parses a continuous hex stream from a string.
    /// </summary>
    public static byte[] ParseHexBytes(this string s)
    {
        if (s == null)
            throw new ArgumentNullException("s");

        if (s.Length == 0)
            return new byte[0];

        if (s.Length % 2 != 0)
            throw new ArgumentException("Source length error", "s");

        int length = s.Length >> 1;
        byte[] result = new byte[length];
        for (int i = 0; i < length; i++)
        {
            result[i] = Byte.Parse(s.Substring(i * 2, 2), NumberStyles.HexNumber);
        }
        return result;
    }

暫無
暫無

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

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