confused
confused

Reputation: 761

Proper python way to clear a bytearray

I miss memset. I have a frame buffer in a class, it has data in it from some other operations, and now I want to clear everything in that frame buffer to 0x00 or 0xFF. I didn't see a clear method in the docs, there's a zfill method that might work. I thought about just calling the init method of the byte array again but wondered if that might cause me some memory trouble down the road.

I'm using python 2.7.

Upvotes: 9

Views: 17691

Answers (3)

nneonneo
nneonneo

Reputation: 179552

If you want to do high-performance manipulations on a framebuffer, consider using NumPy. You can represent your framebuffer as a NumPy array of uint8s:

import numpy as np
fb = np.zeros((480, 640), dtype=np.uint8) # a 640x480 monochrome framebuffer

and then clear the framebuffer very simply:

fb[:] = 0 # or fb[:] = 0xff

The other big advantage is that you get a fast, 2D array - you can do things like fb[80:120, 40:60] to get a rectangular region cheaply, and you can implement draw operations like blitting with very little code. Plus, with np.tobytes you can still obtain a bytes representation.

Upvotes: 3

Ilja Everilä
Ilja Everilä

Reputation: 52937

In [1]: ba = bytearray(range(100))

In [2]: ba
Out[2]: bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abc')

In [3]: ba[:] = b'\x00' * len(ba)

In [4]: ba
Out[4]: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

Upvotes: 4

ForceBru
ForceBru

Reputation: 44888

Python is not C, here you don't need to worry about memory at all much. You just simply do:

a = bytearray("abcd") # initialized it with real data

a = bytearray(5) # just a byte array of size 5 filled with zeros

Upvotes: 6

Related Questions