ManasP
ManasP

Reputation: 31

how to convert binary value to hex decimal in erlang

I am getting binary value like <<"0421">> and this hex representation of 0x0421. and I have to get the bit values of this hex value. and in 2'base representation would be this is 0000 0100 0010 0001.

So I need to get each bit of this hex in Erlang.

If I use list_to_integer(binary_to_list()) I get 421 in integer.

Please help me to convert this binary to hex first and then get the bit value of those hex.

Upvotes: 1

Views: 1907

Answers (4)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

1> integer_to_list(binary_to_integer(<<"0421">>, 16),2).
"10000100001"

See the documentation for the same core erlang module. Especially pay attention to the second parameter of integer_to_list/2.

Upvotes: 1

Pascal
Pascal

Reputation: 14042

You don't say much about the expected format of the result, based on Dogbert proposal, here is a more automated solution.

1> HexToBin = fun(D) -> 
1> S = size(D) * 4,
1> I = binary_to_integer(D,16),
1> << << X >> || <<X:1>> <= << I:S >> >> 
1> end.
#Fun<erl_eval.6.52032458>
2> HexToBin(<<"0421">>). 
<<0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1>>
3> rp(HexToBin(<<"00123456789abcdef0421">>)).
<<0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,1,0,0,0,1,0,1,
  0,1,1,0,0,1,1,1,1,0,0,0,1,0,0,1,1,0,1,0,1,0,1,1,1,1,0,0,
  1,1,0,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1>>
ok
4>

Upvotes: 0

7stud
7stud

Reputation: 48589

Dogbert's solution might get a little tedious with big integers.

bits(HexBin) ->
    bits(
      binary:encode_unsigned(
        binary_to_integer(HexBin, 16)
      ),
      []
    ).

bits(<<Bit:1, Rest/bitstring>>, Acc) ->
    bits(Rest, [Bit|Acc]);
bits(<<>>, Acc) ->
    list_to_tuple(lists:reverse(Acc)).

In the shell:

6> c(my).              
{ok,my}

7> my:bits(<<"0421">>).
{0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}

8> LongResult = my:bits(<<"FFFFFFFFFFFFFF0421">>).        
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,...}

9> io:format("~p~n", [LongResult]).
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}
ok

Upvotes: -1

Dogbert
Dogbert

Reputation: 222040

binary_to_integer/2 accepts a base as the second argument. You can pass 16 to it to convert a hex binary to integer:

1> binary_to_integer(<<"0421">>, 16).
1057
2> 16#0421.
1057

Edit: You can extract each of the 16 bits into 16 variables using pattern matching:

1> Integer = binary_to_integer(<<"0421">>, 16).
1057
2> <<B0:1, B1:1, B2:1, B3:1, B4:1, B5:1, B6:1, B7:1, B8:1, B9:1, B10:1, B11:1, B12:1, B13:1, B14:1, B15:1>> = <<Integer:16>>.
<<4,33>>
3> {B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15}.
{0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}

B0 is now 0, B5 is 1, etc.

Upvotes: 3

Related Questions