00 Votes

Save Binary Data as String

Question by Guest | 2014-11-17 at 20:49

I have some small binary data (byte sequences) which I would like to store just like a string variable. For example, in a database or in a text file.

When just handling those data as a string, sometimes it is working, sometimes not. In most cases, the "string" is just cut off at one illegible character (for example a #0 byte) what is leading to errors when trying to transfer or read the data again.

Is there any trick or workaround I can apply to convert my binary data into a "real" string so that I can read it without any errors?

ReplyPositiveNegative
1Best Answer1 Vote

I think, Base64 is the best for your purpose. Base64 is an algorithm to convert binary data into readable ASCII characters.

As an input, you can use arbitrary binary data with 8 bit, the output string only contains the characters A–Z, a–z, 0–9, + and /.

Here is an example for Lazarus:

uses
  base64;

var
  inputStr, encodedStr, decodedStr: string;
begin
  // arbitrary binary data   
  inputStr := #00#10#09;

  // encode string
  encodedStr := EncodeStringBase64(inputStr);
  // encodedStr is "AAoJ"

  // decode string
  decodedStr := DecodeStringBase64(encodedStr); 
  // decodedStr is again #00#10#09

end;

The example shows how to convert arbitrary binary data (here it is the byte sequence #00 #10 #09 in inputStr) to a readable ASCII string using the function EncodeStringBase64(). The resulting readable string, we are here storing into the variable encodedStr is "AAoJ" for this array of bytes.

You can use DecodeStringBase64() to reverse the string. You can pass an encoded string to this function to get back the original binary data.

When using another programming language, there would also be functions or libraries for Base64.
2014-11-17 at 23:42

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.