Why is << 256 :: size (16) >> present as << 1, 0 >>?

I am reading a binary operator elixir document: https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#binaries-and-bitstrings

In the doc doc:

iex> <<255>>
<<255>>
iex> <<256>> # truncated
<<0>>
iex> <<256 :: size(16)>> # use 16 bits (2 bytes) to store the number
<<1, 0>>

by default, 8 bits of the elixir binary file, if more than 8 bits, the result will be truncated to 0.

But why <<256 :: size(16)>>present <<1, 0>>? I think it should be<<1, 255>>

+3
source share
1 answer

<<1, 0>>is correct. 256 in binary format 0b100000000.

iex(1)> 0b100000000
256

When expanding to 16 bits you will get 0b0000000100000000.

iex(2)> 0b0000000100000000
256

, 0b00000001 0b00000000, 1 0.

iex(3)> <<256::size(16)>>
<<1, 0>>

0 1, :

iex(4)> <<256::little-size(16)>>
<<0, 1>>

, , 1, - 256, - 256 * 256 .., .

iex(5)> <<256::size(16)>>
<<1, 0>>
iex(6)> 1 * 256 + 0 * 1
256
iex(7)> <<123456::size(24)>>
<<1, 226, 64>>
iex(8)> 1 * 256 * 256 + 226 * 256 + 64 * 1
123456
+8

Source: https://habr.com/ru/post/1683314/


All Articles