1

I have tried looking for best practices to convert a standard txt file to binary and am still not understanding it so well, and am wondering if someone can explain it a little better. So lets say I have my_file.txt and want to convert it to my_file.bin. What is the best practice at converting the whole file at once? Can I just write the whole file to a new .bin file? Or do I have to iterate through the file and convert line by line, etc?

I have tried things such as

old_text = File.open('my_file.txt').read
bin_file = File.new("my_file.bin","w+") # I understand w+ may not be the correct option
bin_file.puts(old_text)
bin_file.close

but when trying to read the bin_file nothing is returned. Is there a better practice to completing this?

1
  • 1
    What do you mean by “binary file”? Commented Nov 13, 2014 at 18:24

1 Answer 1

2

Great news! Ruby's string maniupulation has got you covered here:

"some text".unpack('b*')

You can read more on that via http://ruby-doc.org/core-2.1.4/String.html#M000760

You can just do something like this for converting a full file into binary:

old_text = File.open('my_file.txt').read
bin_file = File.new("my_file.bin","w+") # I understand w+ may not be the correct option
bin_file.puts(old_text.unpack('b*'))
bin_file.close
Sign up to request clarification or add additional context in comments.

2 Comments

Oh perfect! Very cool. So would this work as well if I did want to read it line by line? just call that for each line and it would write it to the file right?
Certainly would. Just modify your coding to loop through the file line by line (store the binary into like an array or such) and then dump the binaries from the loop into the new file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.