Skip to content

Instantly share code, notes, and snippets.

@toraritte
Last active November 20, 2018 13:09
Show Gist options
  • Save toraritte/875173d24880ebff62551dc422a9ba5d to your computer and use it in GitHub Desktop.
Save toraritte/875173d24880ebff62551dc422a9ba5d to your computer and use it in GitHub Desktop.
Erlang binaries and unicode
% because 256 needs 9 bits to represent it
% although it is 2^8
62> <<256>>.
<<0>>
% because the segments of an Erlang binary
% has to be divisible by 8. Hence
% 1000 0000, 0
57> <<256:9>>.
<<128,0:1>>
66> <<1024:10>>.
<<0,0:2>>
69> <<1024:11>>.
<<128,0:3>>
% <<2017>> gets truncated to 8 bits automatically
82> f(), <<A:8,B/binary>> = <<2017>>.
<<"á">>
83> B.
<<>>
84> A.
225
% but if you specify the bitnumber to represent it,
% there is no loss, although in this case it cannot be
% matched with /binary because it is not divisible by 8
85> f(), <<A:8,B/binary>> = <<2017:12>>.
** exception error: no match of right hand side value <<126,1:4>>
86> f(), <<A:8,B/bits>> = <<2017:12>>.
<<126,1:4>>
87> B.
<<1:4>>
88> A.
126
% <<128:8>>
% 10, 000000
% << 2, 0:6>>
101> f(), <<A:2,B/bits>> = <<128>>.
<<128>>
102> A.
2
105> B.
<<0:6>>
%-module(binaries).
%-compile(export_all).
%bitlist(Bin) ->
% bitlist(Bin,[]).
%
%bitlist(<<>>,Acc) ->
% lists:reverse(Acc);
%bitlist(<<B:1,Rest/bits>>,Acc) ->
% bitlist(Rest, [B|Acc]).
120> binaries:bitlist(<<8226>>).
[0,0,1,0,0,0,1,0]
121> binaries:bitlist(<<8226:16>>).
[0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0]
122> binaries:bitlist(<<256>>).
[0,0,0,0,0,0,0,0]
123> binaries:bitlist(<<256:9>>).
[1,0,0,0,0,0,0,0,0]
% aaand tha same thing in one line
131> [B || <<B:1>> <= <<8226:16>>].
[0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0]
1> io:format("~ts~n",["\x{2022}"]).
ok
2> io:format("~ts~n",[[8226]]).
ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment