Raoul
Raoul

Reputation: 1892

translating Matlab's bitget() extreme value to python

I got hold of Matlab code containing such a loop:

for n = 1:2^10,
bitget(n-1,10)*2^4;
end;

The problem I have is that Matlab (Octave) apparently adds padding bits to the right as such:

octave:15> bitget(5,1:10)
ans =

   1   0   1   0   0   0   0   0   0   0

and therefore:

octave:14> bitget(5,10)
ans = 0

while python does not add those bits, and therefore yields an error.

For this particular situation, am I right in believing that the above Matlab line bitget(n-1,10)*2^4; can be translated to python as (lambda x: 1 if x == 2**9 else 0)(n)*2**4, since Matlab bitget(5,10) would in my opinion only yield 1 if the binary representation of n spans 10 bits, i.e. 2^9 in this case?

Upvotes: 1

Views: 2134

Answers (1)

beaker
beaker

Reputation: 16791

I think you're misinterpreting the output of Octave. Let's try your example with a different value so we can see what's going on.

>> dec2bin(13)
ans = 1101

>> bitget(13,1:10)
ans =

  1  0  1  1  0  0  0  0  0  0

As you can see, the order of the bits has been reversed. In bitget, bit 1 is the least significant bit, or 2**0 and bit 10 is 2**9. It's not padding on the right, it's just reading 0 bits from a numerical type that's larger than the 4 bits required to store the value 13.

Now, bitget will return 1 whenever the specified bit is 1, regardless of the state of the other bits. So bitget(n-1,10) will return 1 not only for 2**9 = 512, but also for any other value with that bit set; in this case, any value in the range 512..1023. The equality comparison in your Python function won't give you that so you'll need to change it to a bitwise AND:

(lambda x: 1 if x & 2**9 else 0)(n)*2**4

Here I've changed == to & and 2**10 becomes 2**9 to match the value of the 10th bit.

Upvotes: 2

Related Questions