Postgres has specific requirements for binary string storage. All non- printable characters need to be escaped with a \nnn sequence where nnn is the octal representation of the character. See PostgreSQL: Documentation: 8.2: Binary Data Types for details.
So in the type cast code (binary_to_string and string_to_binary) it needs to check whether the value stored in the attributes hash has actually gone through this process, or is just some data that was set but hasn't been persisted yet.
Really I think this whole problem could be solved if we knew the modified state of each column. If the value has been modified from the persisted value, then we would only do the conversion one way (string to binary), otherwise we would only do it the other way (binary to string). Right now this is determined by checking for a \nnn sequence which is unreliable.
Another (better?) approach would be to keep track of whether a particular attribute has gone through the type cast process, caching the casted value, and only calling the type cast code when necessary. This would be preferable anyway for expensive type casts such as this one, or complex geometry data types such as those supported by PostGIS.
--Matt