使用hex(base16)编码将文件读入字节数组

时间:2013-10-11 16:51:10

标签: c# arrays encoding filestream

我正在尝试使用C#将Windows上的纯文本文件(.txt)读入带有base16编码的字节数组中。 这就是我所拥有的:

FileStream fs = null;
try
{
    fs = File.OpenRead(filePath);
    byte[] fileInBytes = new byte[fs.Length];
    fs.Read(fileInBytes, 0, Convert.ToInt32(fs.Length));
    return fileInBytes;
}
finally
{
    if (fs != null)
    {
        fs.Close();
        fs.Dispose();
    }
}

当我读取包含此内容的txt文件时:0123456789ABCDEF 我得到一个128位(或16字节)数组,但我想要的是64位(或8字节)数组。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可以将两个字节作为字符串读取,并使用十六进制数字规范对其进行解析。例如:

var str = "0123456789ABCDEF";
var ms = new MemoryStream(Encoding.ASCII.GetBytes(str));
var br = new BinaryReader(ms);
var by = new List<byte>();
while (ms.Position < ms.Length) {
    by.Add(byte.Parse(Encoding.ASCII.GetString(br.ReadBytes(2)), NumberStyles.HexNumber));
}
return by;

或者就你的情况而言:

        FileStream fs = null;
        try {
            fs = File.OpenRead(filePath);
            using (var br = new BinaryReader(fs)) {
                var by = new List<byte>();
                while (fs.Position < fs.Length) {
                    by.Add(byte.Parse(Encoding.ASCII.GetString(br.ReadBytes(2)), NumberStyles.HexNumber));
                }
                var x = by.ToArray();
            }
        } finally {
            if (fs != null) {
                fs.Close();
                fs.Dispose();
            }
        }
相关问题