Hyungmin Cho
Hyungmin Cho

Reputation: 13

Fractional numbers as array indices in the code, How it works?

I'm having difficulty understanding this code(function) in Python. I think the code below converts a two dimensional image array to a one dimensional buffer array.

However, in this case, I think fractional numbers could be inserted as array indices, because the index of 'buf' array is divided by 8.

(buf[(x + y * self.width) / 8] |= 0x80 >> (x % 8))

Could anyone explain me how the code works even it uses fractional numbers as array indices?

def get_frame_buffer(self, image):
    buf = [0x00] * (self.width * self.height / 8)
    # Set buffer to value of Python Imaging Library image.
    # Image must be in mode 1.
    image_monocolor = image.convert('1')
    imwidth, imheight = image_monocolor.size
    if imwidth != self.width or imheight != self.height:
        raise ValueError('Image must be same dimensions as display \
            ({0}x{1}).' .format(self.width, self.height))

    pixels = image_monocolor.load()
    for y in range(self.height):
        for x in range(self.width):
            # Set the bits for the column of pixels at the current position.
            if pixels[x, y] != 0:
                buf[(x + y * self.width) / 8] |= 0x80 >> (x % 8)
    return buf

Upvotes: 0

Views: 940

Answers (1)

Óscar López
Óscar López

Reputation: 236124

It's not a fractional number; when using Python 2.x, the expression (x + y * self.width) / 8 will be evaluated as an integer division, resulting in an integer index - as long as x, y and self.width are also integers. Just as an example:

23 / 8 # 2.875, but the decimals get truncated
=> 2

By the way, to get the same result in Python 3.x, you'd have to use the // operator.

Upvotes: 1

Related Questions