1

I am trying to decode the bitstring to decimal value. For e.x I have these kind of bitstrings

<<96,64,112,153,9:4>>. I want to convert them to decimal values like you take four bits as a digit (96(01100000) --> 60( first four bits is 6, next four bits is 0) , 64 --> 40 and so on. The output would be 604070999. The last 9:4 represents that you consider 4 bits to represent.

Can anyone help in doing this function erlang.

1 Answer 1

3

If you have a binary rather than a bitstring (i.e., without the trailing 9:4 part), you can apply a hex conversion to each byte within a binary comprehension, then convert the resulting binary to an integer:

1> Bin = <<96,64,112,153>>.
<<96,64,112,153>>
2> binary_to_integer(<< <<(integer_to_binary(B,16))/binary>> || <<B:8>> <= Bin >>).
60407099

The same also works for your bitstring, taking 4 bits at a time instead of 8 in the comprehension:

3> Bits = <<96,64,112,153,9:4>>.
<<96,64,112,153,9:4>>
4> binary_to_integer(<< <<(integer_to_binary(B,16))/binary>> || <<B:4>> <= Bits >>).
604070999

But as @Hynek-Pichi-Vychodil points out in the comments, for the bitstring you don't need the integer_to_binary/2 call at all, but instead can convert each 4-bit digit to its corresponding character by adding $0, the literal for the character 0:

5> binary_to_integer(<< <<($0+B)>> || <<B:4>> <= Bits >>).
604070999
3
  • If you are doing binary_to_integer/1 there is no reason for integer_to_binary(B, 16). binary_to_integer(<< <<($0+B)>> || <<B:4>> <= Bin >>) is sufficient. Oct 6, 2015 at 14:25
  • 1
    @Hynek-Pichi-Vychodil true; I first experimented with handling binary rather than bitstring and so was using <<B:8>> rather than <<B:4>>, and integer_to_binary/2 is needed in that case. I'll happily edit and extend the answer if you like. Oct 6, 2015 at 15:46
  • @SteveVinoski: I will be honored ;-) Oct 6, 2015 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.