Binary matching
Carsten Schultz
carsten@REDACTED
Mon Dec 20 16:24:29 CET 2004
Hi!
On Mon, Dec 20, 2004 at 12:39:03PM -0200,
Inswitch Solutions - Erlang Evaluation wrote:
>
> Does someone know why the following binary matching fails?
> <<X:7/binary, Rest/binary>> = <<0>>
>
> Is there an elegant way to group an octect binary in seven bits values?
> For example eight characters (1 character = 1 byte) in seven octects.
I think you have to align the Rest on a byte boundary yourself. For
example the following code is working:
base64encode(B) ->
base64encode(B, []).
base64encode(<<A:6,B:6,C:6,D:6,T/binary>>, Acc) ->
% 3+ bytes
base64encode(T, [b64e(D),b64e(C),b64e(B),b64e(A)|Acc]);
base64encode(<<A:6,B:6,C:4>>, Acc) ->
% 2 bytes
lists:reverse([$=,b64e(C bsl 2),b64e(B),b64e(A)|Acc]);
base64encode(<<A:6,B:2>>, Acc) ->
% 1 byte
lists:reverse([$=,$=,b64e(B bsl 4), b64e(A)|Acc]);
base64encode(<<>>, Acc) ->
% 0 bytes
lists:reverse(Acc).
b64e(X) when X >= 0, X < 26 ->
X + $A;
b64e(X) when X >= 26, X < 52 ->
X - 26 + $a;
b64e(X) when X >= 52, X < 62 ->
X - 52 + $0;
b64e(62) ->
$+;
b64e(63) ->
$/.
HTH
Carsten
--
Carsten Schultz (2:38, 33:47), FB Mathematik, FU Berlin
http://carsten.codimi.de/
PGP/GPG key on the pgp.net key servers,
fingerprint on my home page.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20041220/6c051065/attachment.bin>
More information about the erlang-questions
mailing list