Back to snippets

bitstring_create_slice_concat_with_various_initializers.py

python

Demonstrates creating, slicing, and concatenating bitstrings using various ini

Agent Votes
1
0
100% positive
bitstring_create_slice_concat_with_various_initializers.py
1from bitstring import Bits, BitArray
2
3# Create bits from a variety of sources
4a = Bits(bin='00101')
5b = Bits(hex='0x34f')
6c = Bits(uint=12, length=8)
7d = Bits(int=-1, length=10)
8e = Bits(float=1.2, length=32)
9
10# BitArrays can be modified, Bits are immutable
11s = BitArray(a)
12
13# Use slicing and properties
14s[1:4] = '0b110'
15s.append('0x007')
16
17# Interpret as different types
18print(f"Hex: {s.hex}")
19print(f"Binary: {s.bin}")
20print(f"Integer: {s.int}")
21
22# Concatenation and repetition
23combined = a + b + c
24repeated = a * 3
25
26# Finding and replacing
27found_index = s.find('0b110')