bwanab
How to read a file of numeric data as a list of integers?
When you read a file with File.read, you get a large binary. I’m reading a file of numeric data that I would like to have in a list of integers, but I haven’t found any straightforward way to do it. I suspect I’m missing something pretty basic.
I.e. instead of
<<77, 84, 104, 100, 0, 0, 0, 6, 0, 1, 0, 10, 0, 192, 77, 84>>
I want:
[77, 84, 104, 100, 0, 0, 0, 6, 0, 1, 0, 10, 0, 192, 77, 84]
Most Liked
wojtekmach
I was curious how to read file contents as charlist and I found:
{:ok, pid} = File.open("mix.exs", [:charlist])
IO.inspect IO.read(pid, :all)
# Outputs: {:ok, 'defmodule ...'}
File.close(pid)
kip
String.length/1 counts the number of graphemes, not code points. So definitely not the right tool for the job you are tackling.
I was surprised to see that \r\n is considered a grapheme cluster but it is according to the Unicode standard.
mpope
Why not just keep it as a binary
if the binary is large, it is allocated to a shared heap and can possibly be more memory efficient. https://medium.com/@mentels/a-short-guide-to-refc-binaries-f13f9029f6e2
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









