[英]Read a file into a byte array with hex (base16) encoding
我正在嘗試使用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字節)數組。 我怎樣才能做到這一點?
您可以將兩個字節作為字符串讀取,並使用十六進制數字規范對其進行解析。 例:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.