String encoding/decoding

Per Gustafsson per.gustafsson@REDACTED
Wed Apr 16 16:25:35 CEST 2003


One of the things that you could use is the bit syntax, what you have then
is a binary and you can decode that into integer, floats and other
binaries like this:

<<A:16/integer,Length:8/integer, NewBinary/binary>> = Binary,

This makes A into an integer consisting of the first 16 bits in the
binary, Length becomes an integer consisting of the next 8 bits and
NewBinary becomes a binary that contains the rest of the bits in the
original binary. The bit syntax is documented in the erlang extensions
after 4.4.

To turn a list of characters into a binary you can use
list_to_binary(List).

Per Gustafsson

On Wed, 16 Apr 2003, Rudolph van Graan wrote:

> Hi all,
>
> A couple of newbie questions here... Hope you can help
>
> Suppose you have a string, for which the Hex representation looks
> something like this:
>
> 	021234053132333435
>
> In reality the string is coded as this:
>
> Byte  1:	Length of Word [2 byte unsigned]
> Bytes 2,3:	High Byte, Low Byte of unsigned work
> Byte  4: 	Length of string to following
> Bytes 5-9:	A 5 character string
>
> So if I want to decode it, I would usually write some code that looks
> like this [in pseudocode, doesn't imply any language]
>
> Len1    = String.GetByte(1)		//Returns a single byte
> Word1   = String.GetWord(Len1)	//Returns a word of len vLen1
> Len2    = String.GetByte(1)		//Returns a single byte
> String1 = String.GetString(vLen2)	//Returns the string "12345"
>
> Now, my question is this. If I want to write an elegant module in
> erlang, that decodes a complex string into its members [members can be
> any type, being byte, word, string, etc etc] into an erlang structure,
> how would I do that? We don't use ASN.1, so my question deals
> specifically with raw strings. You can assume that the string is an
> erlang list and that the output must be an erlang tuple. Also, I would
> like to do exactly the reverse as well - generate these strings from
> tuples.
>
> I can imagine needing a function that takes 1/2/4 integers [byte values]
> from the list and that builds a single 32bit signed/unsigned int and
> also the reverse. The above example is quite simplistic, my typical
> strings would contain a number of encoded elements, the structure of
> which is known.
>
> Any ideas or help would be really appreciated!
>
> Regards,
>
> Rudolph van Graan
>



More information about the erlang-questions mailing list