Converting FOR and Bitwise Operations to Elixir

Good night sirs,

I’m learning Elixir, and today i’m working in a code that encrypt and decrypt using bitwise operations, something simple, and i got stuck in a function. Basically what i need is a function that performs a Bitwise.bsl through elements in a list.

In C++ what i want is this:

unsigned char myFunc()
    unsigned char retn = 0;

    for (int i = 0; i < 5; i++) {
        retn += (1 << i);

    return retn = 0;

I was trying to use Enum.reduce:

Enum.reduce(0..4, 0, fn(x, acc) -> acc + bsl(1, x) end)

But in CPP i got 36 as result, and in Elixir i got 31. o_O

I’m following the right way? Thanks.

1 Like

@allanmfz you are using Bitwise.bsl correctly and 31 does appear to the be the correct answer (and is also what I get when I run the C).

iex> Bitwise.bsl(1, 0)
iex> Bitwise.bsl(1, 1)
iex> Bitwise.bsl(1, 2)
iex> Bitwise.bsl(1, 3)
iex> Bitwise.bsl(1, 4)


1 Like

Something in your C++ implementation is wrong, but I can’t see what it is right now (assuming your return is just a typo and not actually returning 0).

You are summing multiples of two and 1, so your result has to be odd, which 36 obviously isn’t.

And I just checked… I’ve thrown your CPP code at gcc with minor changes (using main and some prints), and I do get 31 as well…


I suspect that last line in your C++ example should be return retn; not return retn = 0;