[erlang-questions] BCD encoding and decodiing

Steve Davis steven.charles.davis@REDACTED
Sat Feb 4 13:29:38 CET 2012


encode(N, Size) ->
	encode0(N, Size * 2, <<>>).

encode0(N, Size, Acc) when Size > 0 ->
	encode0(N div 10, Size - 1, <<(N rem 10):4, Acc/bits>>);
encode0(_, _, Acc) ->
	Acc.

decode(N, Size) ->
	case byte_size(N) of
	Size ->
		decode0(N, 0);
	_ ->
		error
	end.

decode0(<<X:4, Bin/bits>>, Acc) ->
	decode0(Bin, Acc * 10 + X);
decode0(<<>>, Acc) ->
	Acc.

..assuming the "size" argument in decode is a constraint. Not sure you
need it.

regs,
/s

On Feb 3, 11:01 pm, Avinash Dhumane <avin...@REDACTED> wrote:
> Can the following encode and decode functions be written without any library calls from modules 'lists' and 'io_lib'? Please show how. The test cases are included at the end. Thanks
>
> $ cat bcd.erl
> -module(bcd).
> -compile(export_all).
> % pack the digits of an integer as BCD in a given size of binary
> % pad with leading zeros
> encode(N, Size) ->
>   << <<X:4>> || X <- lists:flatten(io_lib:fwrite("~*..0B", [Size*2, N])) >>.
> % unpack the given size of BCD binary into an integer
> % strip leading zeros
> decode(N, Size) ->
>   io_lib:fread("~d", [ X+$0 || <<X:4>> <= <<N:(Size*8)/bits>> ]).
>
> $ erl
> Eshell V5.8.3  (abort with ^G)
> 1> c(bcd).
> {ok,bcd}
> 2> bcd:encode(1, 5).
> <<0,0,0,0,1>>
> 3> bcd:decode(v(2), 5).
> {ok,[1],[]}
> 4> bcd:encode(12345, 5).
> <<0,0,1,35,69>>
> 5> bcd:decode(v(4), 5).
> {ok,[12345],[]}
> 6> bcd:encode(1234567890, 5).
> <<18,52,86,120,144>>
> 7> bcd:decode(v(6), 5).
> {ok,[1234567890],[]}
> 8>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questi...@REDACTED://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list