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)
1
iex> Bitwise.bsl(1, 1)
2
iex> Bitwise.bsl(1, 2)
4
iex> Bitwise.bsl(1, 3)
8
iex> Bitwise.bsl(1, 4)
16

16+8+4+2+1=31

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…

2 Likes

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