[erlang-questions] number->bytes and bytes->number

Matthias Lang <>
Wed May 16 22:25:40 CEST 2007


Gary Jefferson writes:
 > How do I convert a number like "2 bsl 160" to a list
 > of bytes (20 bytes in this case) and vice versa?

Assuming you meant 21 octets, not 20:

  3> Int = 2 bsl 160.
  2923003274661805836407369665432566039311865085952
  4> binary_to_list(<<Int:168>>).
  [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Depending on how general you want this to be you'll need to write a
function to figure out how many bytes the answer will consume. There
are various possible approaches which are left as an exercise.

Matthias



More information about the erlang-questions mailing list