Write integer to file

How do I write an integer to a file without it being seen as the associated ascii character when being turned into bytes?

You can use for example 42u64.to_le_bytes() (returns little endian bytes) there is a similar method for big endian (to_be_bytes) This works for all integer types.

1 Like

Note that 42u64.to_le_bytes() will include the byte 42 in its output, which will appear as the character * (asterisk) if interpreted as ASCII.

Every byte may be interpreted as some character if a program incorrectly interprets it as text. If you want your file to contain human-readable text instead of seemingly-random characters when opened in a text editor, you can serialize your data to a text-based format like JSON or CSV before writing it to a file.

A binary format is often more compact, and usually faster to read and write, but it is not friendly to text editors or other programs that expect the file to contain text.


What is your goal? There are a number of ways to interpret your question as you've asked it.

I read your comment and I decided to use the ini crate to make it easier. I probbably overcomplicated it by attempting serialisation by myself.

Edit: it appears serde_ini is nicer to use.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.