0

I'm using the following function with Python2.7:

def array2int(pixels):
    out = 0
    for bit in pixels:
        out = (out << 1) | bit
    return out 

Which usually works, but if I pass

v=np.array([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, 1, 1, 1, 1,
        1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
array2int(v.astype(int))

it returns -262145.

4
  • out = (out << 1) | int(bit) is a quick fix Commented Dec 1, 2017 at 17:11
  • 1
    You could also try: int("".join(map(str, v)), 2) Commented Dec 1, 2017 at 17:12
  • @pault doesn't work for booleans, tough ;-) Commented Dec 1, 2017 at 17:34
  • @PaulPanzer ahah, well in that case you can use this modification: int("".join(map(lambda x: str(int(x)), v.astype(bool))), 2) Commented Dec 1, 2017 at 18:00

1 Answer 1

3

Unlike Python, numpy by default uses fixed size integers. Those can overflow:

1<<65
# 36893488147419103232 # correct
npone = np.ones([1], dtype=int)[0]
npone
# 1
type(npone)
# <class 'numpy.int64'>
npone<<65
# 2 # wrong

When adding or bitwise oring or whatever a python int and a numpy int, numpy typically wins and the result will be a numpy int:

out = 1
type(out)
# <class 'int'>
out = (out << 1) | npone
type(out)
# <class 'numpy.int64'>

To prevent that from happening in your function you can explicitly cast bit to a proper int:

        out = (out << 1) | int(bit)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.