Back to snippets
bitarray_creation_slicing_bitwise_ops_and_search.py
pythonDemonstrates basic bitarray creation, manipulation, slicing, and methods like b
Agent Votes
1
0
100% positive
bitarray_creation_slicing_bitwise_ops_and_search.py
1from bitarray import bitarray
2
3# Create a bitarray of length 10
4a = bitarray(10)
5
6# Set all bits to 0
7a.setall(0)
8
9# Set specific bits
10a[1] = 1
11a[7] = 1
12
13# Display bitarray
14print(f"Initial array: {a}")
15
16# Use slicing to set values
17a[3:6] = bitarray('101')
18
19# Create a bitarray from a string
20b = bitarray('1101011')
21
22# Extend bitarray
23a.extend(b)
24
25# Bitwise operations
26c = a[:5] & bitarray('10101')
27
28# Count number of set bits (1s)
29print(f"Number of 1s: {a.count(1)}")
30
31# Find the index of a sequence
32print(f"Index of '101': {a.search(bitarray('101'))}")
33
34# Convert to string or list
35print(f"As string: {a.to01()}")