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.
((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));