Question :
I would like to know how to generate a PDF file using a string with binary values, the values should actually turn a text (according to the ASCII table) and be written to PDF. p>
I tried to do this but did not succeed:
string teste = "010001010101111001111111";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(teste);
File.WriteAllBytes(@"C:/teste.pdf", bytes);
What’s wrong with the code? The PDF is created but nothing is written on it, it does not even open.
Answer :
Redirect the bytes of% binary%:
public Byte[] GetBytesFromBinaryString(String binary)
{
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
return list.ToArray();
}
byte[] bytes = GetBytesFromBinaryString("010001010101111001111111");
Finally write the PDF:
File.WriteAllBytes(@"C:/teste.pdf", bytes);
Response based on this answer .
One of the new features in C # 7.0 is binary literals . With it, the solution to this case would be simpler:
var bytes = 0b0100_0101_0101_1110_0111_1111;
File.WriteAllBytes(@"C:/teste.pdf", bytes);
Reference: link