You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Elixir bitstring最后一位默认是1?如何实现全0bitstring?

Why <<1 :: 3>> isn't all zeros, and how to create an all-zero bitstring

Great question! Let's break this down step by step.

Why your initial bitstring has a trailing 1

When you define b = <<1 :: 3>> in Elixir (or Erlang), you're instructing the runtime to encode the integer 1 using exactly 3 bits. Integers are stored in binary form with leading zeros to fill the specified bit length.

Since 1 in binary is just 1, we need two leading zeros to reach the 3-bit requirement, resulting in the binary value 001. That's why when you iterate over each 1-bit segment with your comprehension, you get ["0", "0", "1"]—the first two bits are the padding zeros, and the last is the actual value of the integer you specified.

How to create an all-zero bitstring

There are a few straightforward ways to generate a bitstring where every bit is set to 0:

1. Directly encode 0 with your desired bit size

The simplest method is to use the same syntax as your original code, but replace the integer 1 with 0:

b = <<0 :: 3>>

When you iterate over this bitstring, you'll get ["0", "0", "0"]—since 0 in 3 bits is just 000.

2. Use a bitstring comprehension (dynamic length)

If you need to create a bitstring of variable length, you can build it by concatenating individual 1-bit zero segments:

desired_length = 3
b = for _ <- 1..desired_length, do: <<0::1>>, into: <<>>

This loops desired_length times, adding a 1-bit zero each iteration, and collects all segments into a single bitstring.

3. Erlang equivalent

For Erlang developers, the direct approach is nearly identical:

B = <<0:3>>.

Or for dynamic lengths, use a list comprehension:

DesiredLength = 3,
B = <<0:1 || _ <- lists:seq(1, DesiredLength)>>.

All of these methods will produce a bitstring where every bit is 0.

内容的提问来源于stack exchange,提问作者leifericf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:47:42