Moon soon
Moon soon

Reputation: 2856

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

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

In doc:

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

the default is 8 bits of elixir binary, if over 8 bits, the result will truncate to 0.

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

Upvotes: 3

Views: 125

Answers (1)

Dogbert
Dogbert

Reputation: 222288

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

iex(1)> 0b100000000
256

When you extend it to 16 bits you get 0b0000000100000000.

iex(2)> 0b0000000100000000
256

When you split it into two bytes in big-endian byte order, you get 0b00000001 and 0b00000000, which is 1 and 0.

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

In little-endian byte order, you'll get 0 and 1 as the order of the bytes is reversed:

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

To get the original number back from big-endian bytes, you can think of it is multiplying the last number by 1, the second last by 256, the third last by 256 * 256 and so on, and then summing all of them.

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

Upvotes: 9

Related Questions