3. December 2008 18:19
Okay, so C# (.Net) has some awesome functionality for creating a hex string from a numeric value. But what if you need an octal string for a binary value. The real key is realizing that you need to move the value by 3 bits at a time for each octal number, and to XAND the value by 7 which is the highest value an octal number can hold.
public static string EncodeOctalString(byte value)
{
//convert to int, for cleaner syntax below.
int x = (int)value;
//return octal encoding \ddd of the character value.
return string.Format(
@"\{0}{1}{2}",
((x >> 6) & 7),
((x >> 3) & 7),
(x & 7)
);
}
Below is the reverse method, to convert from an octal value back into a byte.
public static byte DecodeOctalString(string octalValue)
{
int a = int.Parse(octalValue.Substring(1, 1));
int b = int.Parse(octalValue.Substring(2, 1));
int c = int.Parse(octalValue.Substring(3, 1));
return (byte)((a<<6) | (b<<3) | (c));
}
Hope it helps someone out there. It's actually a problem I solved several years ago when working with inputting data into PostgreSQL. The reverse method is what I needed today in order to be able to decode a javascript escaped string. My next post will show what this is about.