jeramyRR

jeramyRR

How to pad a binary with 0's?

Hi all,

I’m trying to write out a string, in binary, using Elixir’s <<>> syntax, and am having a dumb moment. I have a requirement where if a template name string isn’t 16 characters long then the remaining bytes must be padded with zeros.

Here is the header I’m trying to write:

┌──────────────────┬───────────┬────────────────┬──────────────────┬───────────┬───────────┐
│       TAG        │ Label Len │ Content Length │   Template Name  │  Contents │ Signature │
├──────────────────┼───────────┼────────────────┼──────────────────┼───────────┼───────────┤
│4x Unsigned Chars │    u16    │      u64       │  16byte char str │           │           │
└──────────────────┴───────────┴────────────────┴──────────────────┴───────────┴───────────┘

What I have so far is:

label_bin =
      <<"TAG1", label_metadata.label_len::16, label_metadata.content_length::64>>

I’m not sure how to write the Template name in the same way as above. Do I need to create another IO structure and just append the 0’s?

Thanks,
Jeramy

Marked As Solved

Sebb

Sebb

template_name = "foo"
pad = 16 - byte_size(template_name)
<<template_name::binary, 0::pad*8>>

Edit: Note that this may crash: How to pad a binary with 0's? - #6 by al2o3cr

Also Liked

Sebb

Sebb

here: Kernel.SpecialForms — Elixir v1.12.3

also useful: binary — OTP 29.0.2 (stdlib 8.0.1)
(but there is nothing there that helps you with this, would be nice).

Don’t use String for this.

al2o3cr

al2o3cr

The given solution will crash if template_name is longer than 16 characters; this may be fine, depending on where the name is coming from etc.

If crashing isn’t acceptable, than the string will need to be truncated. You can do both the padding and the truncating together with a little pattern matching:

<<padded_and_trimmed::bits-size(128), _::bits>> = <<template_name::binary, 0::128>>

This works by initially padding template_name with 16 bytes of zeros, then taking only the first 16 bytes of the remainder.

The truncation can also be done as part of a larger step, like your label_bin:

padded_name = <<template_name::binary, 0::128>>
label_bin =
      <<"TAG1", label_metadata.label_len::16, label_metadata.content_length::64, padded_name::bits-size(128), ...>>

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New

Other popular topics Top

Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement