[erlang-questions] map over bitstring

David Mercer dmercer@REDACTED
Wed Oct 27 21:17:12 CEST 2010


On Wednesday, October 27, 2010, rgowka1 wrote:

> How can I convert a bitstring that has only characters $1 and $0 into a
> binary.
> 
> <<0,1,0,0,1,0,0,1,0>> to << 2#0100100100 >> to << 292 >>
> 
> something similar to io_lib:fread("~2u", [$0,$1,$0,$0,$1,$0,$0,$1,$0])
> but that works on bitstring instead of string.

Not entirely sure what you are trying to do.  << 292 >> is an 8-bit byte
equivalent to << 36 >> or << "$" >>; <<0,1,0,0,1,0,0,1,0>> is a 9-byte
binary; and 2#0100100100 is an integer specified by a 10-digit base-2
number.

Assuming that you erroneously added a 0 to the base-2 number, 2#010010010 =
146.  You can get that number as follows:

	Bits = <<0,1,0,0,1,0,0,1,0>>,
	NumBits = size(Bits),
	<< Val:NumBits >> = << <<Bit:1>> || <<Bit:8>> <= Bits >>,
	Val.

Cheers,

David



More information about the erlang-questions mailing list