[erlang-questions] Binaries

zxq9 zxq9@REDACTED
Wed Jun 20 03:21:01 CEST 2018

On 2018年6月19日 火曜日 16:32:49 Bob Cowdery wrote:
> If I have a number, say 1450000001 and I want to represent that as a 
> binary in the form
>   <<16#14,16#50,16#00,16#00,16#01>> what's the best way.
> I'm not sure what list_to_binary(integer_to_list(1450000001)) which 
> prints as <<"1450000001">> produces but I guess its 10 bytes not 5.

Binary syntax can be a bit of a wonderland at first.

The form you present above works just fine. Keep in mind that it yields the following:

  1> <<16#14,16#50,16#00,16#00,16#01>>.

If we want to encode it using your original decimal representation (or as an integer programatically generated as a variable), and pack it into the same 40-bit space (5 8-bit bytes):

  2> <<1450000001:40>>.

What, what? These aren't the same!

There are two reasons:
 - The hexadecimal modifier 16# means 10#14 =/= 16#14
 - Your version splits this integer value up into decimal-determined fields

It appears that you don't actually want to encode the number 1450000001, but rather want five 8-bit fields carrying the values 14, 50, 00, 00, and 01, in that order. Is this correct?

If you're starting with an integer that is *actually* 1,450,000,001 and you want to break it up by its decimal value then you'll want to div/rem it down by 100s to break it into chunks and then encode each chunk:

  1> Split = fun
  1>   Chunk(0, Parts) -> Parts;
  1>   Chunk(Z, Parts) -> Chunk(Z div 100, [Z rem 100 | Parts])
  1> end.
  2> Pack = fun
  2>   Stuff([], Bin)      -> Bin;
  2>   Stuff([H | T], Bin) -> Stuff(T, <<Bin/binary, H:8>>) 
  2> end.
  3> N = 1450000001.
  4> Splitted = Split(N, []).
  5> Packed = Pack(Splitted, <<>>).


On your sensor side you should have this "number" as a byte array of some sort. Figure out what the field sizes are in bits or bytes and interpret it accordingly. That's a much more sane way to do business.


More information about the erlang-questions mailing list