Wednesday, March 15, 2006

.NET : Converting two ASCII bytes to one hex byte

One of the big disadvantages of tools like Visual Studio is that they hide the underlying machine operations from the user. As a result, most developers haven't a clue about hex , bit shifting etc. To those oldies who started in the assembler / DOS era, hex manipulation is something they ate / slept and breathed.

Quickly, what's 0x7e in decimal?

Waaay to slow. The answer is 126. (7 x 16) + 14.

So I'm sitting with a whole bunch of "wunderkinden" (who think they know everything)
and not one of them could figure out how to "un URL encode" in C#

i.e. convert %7F (three ASCII bytes) to 1 hex byte (0x7F).

Here's one way:

String urlEncode = "%7F";

String hString = "0123456789ABCDEF";

String sHighVal = urlEncode.Substring (1,1);
String sLowVal = urlEncode.Substring (2,1);

int iHighVal = hString.IndexOf (sHighVal);
int iLowVal = hString.IndexOf (sLowVal);

iHighVal = iHighVal << 4;

int result = iHighVal | iLowVal;

Enjoy!

No comments: