2

I must confess that the erlang binary syntax has confused me.

I want to issue the file:change_mod/2 function but to prepare the integer value that contains the file mode ( 755, 740, etc ) I want to construct it from a list of boolean atoms such as:

[ true, true, true, true, false, true, true, false, true ] 

which would be equivalent to 111 101 101 = 755 in octal (base8)

I am unable to find a direct way to do this with bit string representation.

4

3 回答 3

3

另一种方法:

-module(bits).

-export([bit_flag/1]).

bit_flag(Flags) ->
    Bits = length(Flags),
    <<X:Bits/integer>> = << <<(to_bit(Flag)):1/integer>> || Flag <- Flags >>,
    X.

to_bit(true) -> 1;
to_bit(false) -> 0.
于 2013-06-05T06:26:27.923 回答
2

一种方法可能是这样的:

List = [ true, true, true, true, false, true, true, false, true ],

{_, Mode} = lists:foldr(
    fun(A, {M, S}) -> {M * 2, (A * M) + S } end,
    {1, 0},
    [case X of true -> 1; false -> 0 end || X <- List]
).

Mode =:= 8#755.
true

io:format("~.8B~n", [Mode]).
755
ok

或者作为一个模块:

-module(change_mode_utils).

-export([bool_list_to_mode/1]).

-spec bool_list_to_mode(List::[boolean()]) -> integer().
bool_list_to_mode(List) when is_list(List) ->
    {_, Mode} = lists:foldr(
        fun(true,  {M, S}) -> { M * 2, M + S };
           (false, {M, S}) -> { M * 2,     S } end,
        {1, 0},
        List
    ),
    Mode.

证明

1> c(change_mode_utils).
{ok,change_mode_utils}
2> change_mode_utils:bool_list_to_mode(
    [ true, true, true, true, false, true, true, false, true ]
) =:= 8#755.
true
于 2013-06-04T22:42:47.413 回答
1

到目前为止,这是我想出的:

1> Inp = [true, true, true, true, false, true, true, false, true].
[true,true,true,true,false,true,true,false,true]
2> Lst = [if X =:= true -> 1; X =:= false -> 0 end || X <- Inp].
[1,1,1,1,0,1,1,0,1]
3> B = lists:foldl(fun(A, AccIn) -> <<AccIn/bits,A:1>> end, <<>>, Lst).
<<246,1:1>>
4> Int = binary:decode_unsigned(<<0:((8-(bit_size(B) rem 8)) rem 8), B/bits>>).
493
5> io:fwrite("~.8B~n", [Int]).
755
ok
6>

函数binary:decode_unsigned期望输入值是一个字节的倍数,因此我们可能必须填充它。

于 2013-06-04T23:21:56.273 回答