[erlang-questions] BCD encoding and decodiing

Avinash Dhumane avinash@REDACTED
Sat Feb 4 06:01:21 CET 2012


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> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120204/95fa2df2/attachment.htm>


More information about the erlang-questions mailing list