Command Line Hex Representation of File or Standard Input

In my last post (Populating Clipboard from Console App) I showed a *simple* command line app to copy something to the clipboard. The "something" I wanted to copy to the clipboard was the output of this simple app -- a command-line application to take a file (or any standard input data) and return the hex representation of the input. That is, if you have a file with "Walden" then this app will return "57616C64656E"

Why in the world would I do this? Well there are several reasons, including looking to see the actual byte values in a file if you're checking for unicode/code-page issues, or checking to see if there are hidden null values at the end of a file, but the main reason I wanted it was to give me the hex representation of a CLR DLL so I could create a CLR assembly in SQL Server. You can include the path to the DLL in the CREATE ASSEMBLY statement, or you can include the actual DLL bits. I prefer to include the bits, but that's another post.

I created the AsHex command line application to do this for me. It simply takes what's passed in as standard input and writes its hex representation to standard output -- very unix-like, hard to believe for a Windows bigot like me, I know.

Want to get the hex representation of some text? You can 'echo' it into AsHex like this:

echo Test Text | ashex

Do that and you'll get this as output:


Note that echo honors everything up to the pipe character, including the trailing spaces (0x20), and echo adds a CRLF (0x0d0a) to the end of your input.

Now being a standard command line tool you can also redirect standard input with the < sign. So to accomplish what I wanted (the hex rep of a dll) I can type:

ashex < SqlHashFunctions.dll

and I'll get something that looks like this (all on one line):


The code for this is straightforward:

We simply open the standard input stream and read the bytes one by one and write the hex representation ({0:X2}) to the console.

And if I want the output on the clipboard then I can combine this with the clipboard application and do this:

ashex < SqlHashFunctions.dll | clipboard

and I'll have the hex representation of the dll on the clipboard, ready to be pasted into my SQL script.

No comments:

Post a Comment