DerpyNerd
DerpyNerd

Reputation: 4813

Read a file into a byte array with hex (base16) encoding

I'm trying to read a plain text file (.txt) on Windows using C# into a byte array with base16 encoding. This is what I've got:

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();
    }
}

When I read a txt file with this content: 0123456789ABCDEF I get a 128 bits (or 16 bytes) array but what I wanted is a 64 bits (or 8 bytes) array. How can I do this?

Upvotes: 0

Views: 2750

Answers (1)

Deathspike
Deathspike

Reputation: 8800

You can read two bytes as a string and parse it using a hex number specification. Example:

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;

Or in your case something along these lines:

        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();
            }
        }

Upvotes: 2

Related Questions