Skip to content

Instantly share code, notes, and snippets.

@DreamVB
Created July 10, 2016 19:25
Show Gist options
  • Save DreamVB/ff00b00998f4d8f413f726c6bd723d66 to your computer and use it in GitHub Desktop.
Save DreamVB/ff00b00998f4d8f413f726c6bd723d66 to your computer and use it in GitHub Desktop.
Convert Binary To Hex By DreamVB
using System;
using System.Text;
using System.IO;
namespace bin2hex
{
class bin2hex
{
private static bool _abort = false;
private static StringBuilder BinaryToHex(string Filename)
{
StringBuilder sb = new StringBuilder();
string LineBuff = string.Empty;
string sHex = string.Empty;
FileInfo fi = null;
int b = 0;
try
{
fi = new FileInfo(Filename);
using (StreamReader br = new StreamReader(File.OpenRead(fi.FullName)))
{
//Append filename as first item
for (int x=0;x<br.BaseStream.Length;x++)
{
//Read byte
//Convert byte to hex.
sHex = br.BaseStream.ReadByte().ToString("X2");
//Build line
LineBuff += sHex + " ";
if (LineBuff.Length >= 54)
{
sb.AppendLine(LineBuff.TrimEnd());
LineBuff = string.Empty;
}
}
//Append remaining line
sb.AppendLine(LineBuff.TrimEnd());
//Close file.
br.Close();
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
_abort = true;
}
return sb;
}
static int Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Incorrect syntext.");
return 0;
}
StringBuilder sb = BinaryToHex(args[0]);
if (_abort) { return 0; }
try
{
using (StreamWriter sw = new StreamWriter(File.OpenWrite(args[1])))
{
//Write to file.
sw.Write(sb.ToString());
//Close file
sw.Close();
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment