Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EDIT: <strong>This code was written a long time before the question edit which fleshed out the requirements.</strong></p> <p>Given that a single line of C can contain a huge number of statements, it's almost certainly true without being useful.</p> <p>In C# I'd almost certainly write it in more than 10 lines, even though it would be <em>feasible</em> in 10. I'd separate out the "parse nybble" part from the "convert a string to a byte array" part.</p> <p>Of course, if you don't care about spotting incorrect lengths etc, it becomes a bit easier. Your original text also contained spaces - should those be skipped, validated, etc? Are they part of the <em>required</em> input format?</p> <p>I rather suspect that the comment was made without consideration as to what a pleasant, readable solution would look like.</p> <p>Having said that, here's a hideous version in C#. For bonus points, it uses LINQ completely inappropriately in an effort to save a line or two of code. The lines could be longer, of course...</p> <pre><code>using System; using System.Linq; public class Test { static void Main(string[] args) { byte[] data = ParseHex(args[0]); Console.WriteLine(BitConverter.ToString(data)); } static byte[] ParseHex(string text) { Func&lt;char, int&gt; parseNybble = c =&gt; (c &gt;= '0' &amp;&amp; c &lt;= '9') ? c-'0' : char.ToLower(c)-'a'+10; return Enumerable.Range(0, text.Length/2) .Select(x =&gt; (byte) ((parseNybble(text[x*2]) &lt;&lt; 4) | parseNybble(text[x*2+1]))) .ToArray(); } } </code></pre> <p>(This is avoiding "cheating" by using any built-in hex parsing code, such as <code>Convert.ToByte(string, 16)</code>. Aside from anything else, that would mean losing the use of the word nybble, which is always a bonus.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload