Skip to content

Instantly share code, notes, and snippets.

@jakesays-old
Last active May 13, 2018 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakesays-old/543d8e02fd5b1dc1559cdc8986872c68 to your computer and use it in GitHub Desktop.
Save jakesays-old/543d8e02fd5b1dc1559cdc8986872c68 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ParseHex
{
class Program
{
static void Main()
{
var bits = File.ReadAllBytes(@"SOME FILE HERE");
var bitsLen = bits.Length;
// bitsLen = 2048;
var str = BitConverter.ToString(bits, 0, bitsLen).Replace("-", "");
var lines = BreakIntoLines(str, 512);
var strrn = string.Join("\r\n", lines);
Console.WriteLine($"str.len = {str.Length}");
Console.WriteLine($"strrn.length = {strrn.Length}");
var sw = new Stopwatch();
sw.Start();
var bits2 = ParseHexString(strrn);
sw.Stop();
Console.WriteLine($"Time: {sw.ElapsedMilliseconds}ms");
if (bits.Length != bits2.Length)
{
Console.WriteLine($"{bitsLen} != {bits2.Length}");
return;
}
for (var i1 = 0; i1 < bits.Length; i1++)
{
if (bits[i1] != bits2.Bits[i1])
{
Console.WriteLine($"Bytes differ at {i1}: orig {bits[i1]:X2} new: {bits2.Bits[i1]:X2}");
}
}
}
private static (byte[] Bits, int Length) ParseHexString(string hex)
{
var destLength = hex.Length / 2;
var source = hex.ToCharArray();
var dest = new byte[destLength];
// int srcIndex = 0;
int Nibble(int c)
{
if (c >= 'A')
{
return (c - 'A') + 10;
}
return c - '0';
}
var dstIndex = 0;
for (var srcIndex = 0; srcIndex < hex.Length; srcIndex++)
{
var nb = source[srcIndex++];
if (nb == '\r' || nb == '\n')
{
continue;
}
var b = Nibble(nb) << 4 | Nibble(source[srcIndex]);
dest[dstIndex++] = (byte) b;
}
return (dest, dstIndex);
}
private static List<string> BreakIntoLines(string text, int width)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
if (width < 1)
{
throw new ArgumentOutOfRangeException(nameof(width));
}
var pos = 0;
var eol = text.Length;
var lines = new List<string>();
do
{
var len = eol - pos;
len = Math.Min(len, width);
var line = text.Substring(pos, len);
lines.Add(line);
pos += len;
} while (eol > pos);
return lines;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment