OctetString.ToString() method

Unlike the name of the class, OctetString doesn’t really store text strings as would be expected, but any type of byte based data.

Because data in the OctetString is just a series of bytes, there is no guarantee that it is printable so some fancy footwork is required to perform the ToString() method operation.

In the current implementation, OctetString.ToString() tries to determine if the value contained within the class is binary and therefore unreadable, or ASCII and therefore printable. This is done by scanning the class data for values that are less then 32 (excluding the new line characters which are considered printable) or greater then 127. Values outside of this range are not considered ASCII text so assumption is that class value is binary and special output format is required.

Now, if the value is determined to be all text then there is no problem, convert the byte array to a System.String class and return the result.

Problem is that if the value is binary, then converting the class data to a System.String would result in a bunch of junk that is not printable. When this happens, OctetString.ToString() method calls OctetString.ToHexString() which will print out each byte value as a 2 character hex value representing the byte value.

As you can imagine, this method of trying to “guess” what type of value is contained within the class is not very exact. One example is that you have binary data that just happens to fall within the ASCII character range and shouldn’t be represented as a printable string.

In cases where you know you will be receiving binary data that is not in the text format, you should use OctetString.ToHexString() to get predictable results.

There is an additional ToString??? method provided for MAC addresses. I have a need for specific vendor format MAC address that groups MAC address bytes into groups of 2 delimited by “.”. For example: 0008.0102.0304. To get this kind of output, you can use OctetString.ToMACAddressString(). Please note that this method will only work if the OctetString class data is exactly 6 bytes long. Any other data length will result in a zero length string being returned.