or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdcore-operations.mdcreation-conversion.mdindex.mdutility-functions.md

creation-conversion.mddocs/

0

# Creation and Conversion

1

2

Comprehensive methods for creating bitarrays from various sources and converting to different formats including integers, hex strings, bytes, and other representations.

3

4

## Capabilities

5

6

### Object Creation Functions

7

8

Utility functions for creating bitarrays with specific patterns and properties.

9

10

```python { .api }

11

def zeros(length: int, endian: Optional[str] = None) -> bitarray:

12

"""

13

Create bitarray of all zeros.

14

15

Args:

16

length: Number of bits

17

endian: Bit-endianness ('big' or 'little'), uses default if None

18

19

Returns:

20

bitarray with all bits set to 0

21

"""

22

23

def ones(length: int, endian: Optional[str] = None) -> bitarray:

24

"""

25

Create bitarray of all ones.

26

27

Args:

28

length: Number of bits

29

endian: Bit-endianness ('big' or 'little'), uses default if None

30

31

Returns:

32

bitarray with all bits set to 1

33

"""

34

```

35

36

**Usage Examples:**

37

38

```python

39

from bitarray.util import zeros, ones

40

41

# Create patterns

42

a = zeros(8) # bitarray('00000000')

43

b = ones(5) # bitarray('11111')

44

c = zeros(12, 'little') # 12 zeros, little-endian

45

```

46

47

### Random Generation

48

49

Functions for generating random bitarrays with various probability distributions.

50

51

```python { .api }

52

def urandom(length: int, endian: Optional[str] = None) -> bitarray:

53

"""

54

Generate cryptographically random bitarray using os.urandom().

55

56

Args:

57

length: Number of bits

58

endian: Bit-endianness

59

60

Returns:

61

Random bitarray

62

"""

63

64

def random_k(n: int, k: int, endian: Optional[str] = None) -> bitarray:

65

"""

66

Generate pseudo-random bitarray with exactly k bits set.

67

Requires Python 3.9+.

68

69

Args:

70

n: Total number of bits

71

k: Number of bits to set to 1

72

endian: Bit-endianness

73

74

Returns:

75

Random bitarray with exactly k ones

76

"""

77

78

def random_p(n: int, p: float = 0.5, endian: Optional[str] = None) -> bitarray:

79

"""

80

Generate pseudo-random bitarray where each bit has probability p of being 1.

81

Requires Python 3.12+.

82

83

Args:

84

n: Number of bits

85

p: Probability of each bit being 1 (0.0 to 1.0)

86

endian: Bit-endianness

87

88

Returns:

89

Random bitarray

90

"""

91

```

92

93

**Usage Examples:**

94

95

```python

96

from bitarray.util import urandom, random_k, random_p

97

import random

98

99

# Set seed for reproducible results

100

random.seed(42)

101

102

# Random generation

103

a = urandom(16) # Cryptographically random

104

b = random_k(20, 5) # Exactly 5 bits set in 20 bits

105

c = random_p(100, 0.3) # Each bit has 30% chance of being 1

106

```

107

108

### Byte Conversion

109

110

Methods for converting between bitarrays and byte representations.

111

112

```python { .api }

113

def frombytes(self, a: Union[bytes, bytearray]) -> None:

114

"""

115

Append bits from bytes/bytearray to bitarray.

116

117

Args:

118

a: Bytes or bytearray to convert

119

"""

120

121

def tobytes(self) -> bytes:

122

"""

123

Convert bitarray to bytes object.

124

Padding bits are set to 0.

125

126

Returns:

127

bytes representation of bitarray

128

"""

129

130

def fromfile(self, f: BinaryIO, n: int = -1) -> None:

131

"""

132

Read bits from file and append to bitarray.

133

134

Args:

135

f: Binary file object

136

n: Maximum number of bytes to read (-1 for all)

137

"""

138

139

def tofile(self, f: BinaryIO) -> None:

140

"""

141

Write bitarray to file as bytes.

142

143

Args:

144

f: Binary file object to write to

145

"""

146

147

def pack(self, a: Union[bytes, bytearray]) -> None:

148

"""

149

Pack bytes into bitarray, extending with bits from bytes."""

150

151

def unpack(self, zero: bytes = b'\\x00', one: bytes = b'\\x01') -> bytes:

152

"""

153

Unpack bitarray to bytes, using specified bytes for 0 and 1 bits."""

154

```

155

156

**Usage Examples:**

157

158

```python

159

from bitarray import bitarray

160

161

# Byte operations

162

a = bitarray()

163

a.frombytes(b'\\x5A\\x3C') # Append bytes as bits

164

byte_data = a.tobytes() # Convert to bytes

165

166

# File operations

167

with open('data.bin', 'rb') as f:

168

a.fromfile(f, 10) # Read 10 bytes from file

169

170

with open('output.bin', 'wb') as f:

171

a.tofile(f) # Write to file

172

173

# Packing/unpacking

174

a.pack(b'\\xFF\\x00') # Pack bytes as individual bits

175

unpacked = a.unpack(b'0', b'1') # Custom 0/1 representations

176

```

177

178

### String Representations

179

180

Methods for converting between bitarrays and string formats.

181

182

```python { .api }

183

def to01(self, group: int = 0, sep: str = '') -> str:

184

"""

185

Convert bitarray to '01' string representation.

186

187

Args:

188

group: Group bits (0 for no grouping)

189

sep: Separator between groups

190

191

Returns:

192

String of '0' and '1' characters

193

"""

194

195

def tolist(self) -> list[int]:

196

"""

197

Convert bitarray to list of integers (0s and 1s).

198

199

Returns:

200

List of 0 and 1 integers

201

"""

202

```

203

204

**Usage Examples:**

205

206

```python

207

a = bitarray('10110011')

208

209

# String representations

210

s1 = a.to01() # '10110011'

211

s2 = a.to01(4, ' ') # '1011 0011'

212

s3 = a.to01(2, '-') # '10-11-00-11'

213

214

# List conversion

215

lst = a.tolist() # [1, 0, 1, 1, 0, 0, 1, 1]

216

```

217

218

### Hexadecimal Conversion

219

220

Functions for converting between bitarrays and hexadecimal representations.

221

222

```python { .api }

223

def ba2hex(a: bitarray, group: int = 0, sep: str = '') -> str:

224

"""

225

Convert bitarray to hexadecimal string.

226

227

Args:

228

a: Input bitarray

229

group: Group hex digits (0 for no grouping)

230

sep: Separator between groups

231

232

Returns:

233

Hexadecimal string representation

234

"""

235

236

def hex2ba(s: str, endian: Optional[str] = None) -> bitarray:

237

"""

238

Convert hexadecimal string to bitarray.

239

240

Args:

241

s: Hexadecimal string (with or without '0x' prefix)

242

endian: Bit-endianness

243

244

Returns:

245

bitarray from hex string

246

"""

247

```

248

249

**Usage Examples:**

250

251

```python

252

from bitarray import bitarray

253

from bitarray.util import ba2hex, hex2ba

254

255

# Hex conversion

256

a = bitarray('1010110011110000')

257

hex_str = ba2hex(a) # 'AB3F0'

258

hex_grouped = ba2hex(a, 2, ' ') # 'AB 3F 0'

259

260

# From hex

261

b = hex2ba('5A3C') # Convert hex to bitarray

262

c = hex2ba('0xFF00') # With '0x' prefix

263

d = hex2ba('ABCD', 'little') # Little-endian

264

```

265

266

### Base Conversion

267

268

Functions for converting bitarrays to and from various number bases.

269

270

```python { .api }

271

def ba2base(n: int, a: bitarray, group: int = 0, sep: str = '') -> str:

272

"""

273

Convert bitarray to base-n string representation.

274

275

Args:

276

n: Target base (2-36)

277

a: Input bitarray

278

group: Group digits (0 for no grouping)

279

sep: Separator between groups

280

281

Returns:

282

Base-n string representation

283

"""

284

285

def base2ba(n: int, s: str, endian: Optional[str] = None) -> bitarray:

286

"""

287

Convert base-n string to bitarray.

288

289

Args:

290

n: Source base (2-36)

291

s: Base-n string

292

endian: Bit-endianness

293

294

Returns:

295

bitarray from base-n string

296

"""

297

```

298

299

**Usage Examples:**

300

301

```python

302

from bitarray import bitarray

303

from bitarray.util import ba2base, base2ba

304

305

a = bitarray('11010110')

306

307

# Base conversions

308

binary = ba2base(2, a) # '11010110' (binary)

309

octal = ba2base(8, a) # '326' (octal)

310

decimal = ba2base(10, a) # '214' (decimal)

311

hex_str = ba2base(16, a) # 'D6' (hexadecimal)

312

313

# From base-n strings

314

b = base2ba(8, '755') # From octal

315

c = base2ba(16, 'CAFE') # From hex

316

d = base2ba(3, '12021') # From base-3

317

```

318

319

### Integer Conversion

320

321

Functions for converting between bitarrays and integer values.

322

323

```python { .api }

324

def ba2int(a: bitarray, signed: bool = False) -> int:

325

"""

326

Convert bitarray to integer.

327

328

Args:

329

a: Input bitarray

330

signed: Interpret as signed integer (two's complement)

331

332

Returns:

333

Integer value

334

"""

335

336

def int2ba(i: int,

337

length: Optional[int] = None,

338

endian: Optional[str] = None,

339

signed: bool = False) -> bitarray:

340

"""

341

Convert integer to bitarray.

342

343

Args:

344

i: Integer value

345

length: Bit length (auto-determined if None)

346

endian: Bit-endianness

347

signed: Use two's complement for negative numbers

348

349

Returns:

350

bitarray representation of integer

351

"""

352

```

353

354

**Usage Examples:**

355

356

```python

357

from bitarray import bitarray

358

from bitarray.util import ba2int, int2ba

359

360

# Integer to bitarray

361

a = int2ba(42) # Auto-length

362

b = int2ba(42, 8) # Fixed 8-bit length

363

c = int2ba(-10, 8, signed=True) # Signed representation

364

365

# Bitarray to integer

366

val1 = ba2int(bitarray('1010')) # 10 (unsigned)

367

val2 = ba2int(bitarray('1010'), signed=True) # -6 (signed)

368

369

# Large integers

370

big_int = 2**100 + 42

371

big_ba = int2ba(big_int)

372

recovered = ba2int(big_ba) # == big_int

373

```

374

375

### Special Creation Functions

376

377

Additional utility functions for creating specialized bitarrays.

378

379

```python { .api }

380

def gen_primes(n: int, endian: Optional[str] = None, odd: bool = False) -> bitarray:

381

"""

382

Generate bitarray representing prime numbers up to n using Sieve of Eratosthenes.

383

384

Args:

385

n: Upper limit

386

endian: Bit-endianness

387

odd: Only consider odd numbers if True

388

389

Returns:

390

bitarray where bit i is 1 if i is prime

391

"""

392

393

def bits2bytes(n: int) -> int:

394

"""

395

Calculate number of bytes needed to store n bits.

396

397

Args:

398

n: Number of bits

399

400

Returns:

401

Number of bytes required

402

"""

403

```

404

405

**Usage Examples:**

406

407

```python

408

from bitarray import bits2bytes

409

from bitarray.util import gen_primes

410

411

# Prime generation

412

primes = gen_primes(100) # Primes up to 100

413

odd_primes = gen_primes(100, odd=True) # Only odd primes

414

415

# Check if number is prime

416

is_17_prime = primes[17] # True

417

is_18_prime = primes[18] # False

418

419

# Byte calculation

420

bytes_needed = bits2bytes(25) # 4 bytes needed for 25 bits

421

```

422

423

### Package Utility Functions

424

425

Additional package-level utility functions for configuration and testing.

426

427

```python { .api }

428

def get_default_endian() -> str:

429

"""

430

Get the default bit-endianness for new bitarray objects.

431

432

Returns:

433

Default endianness ('big' or 'little')

434

"""

435

436

def test(verbosity: int = 1) -> TextTestResult:

437

"""

438

Run bitarray test suite and return results.

439

440

Args:

441

verbosity: Test output verbosity level (0=quiet, 1=normal, 2=verbose)

442

443

Returns:

444

unittest.runner.TextTestResult object

445

"""

446

```

447

448

**Usage Examples:**

449

450

```python

451

from bitarray import get_default_endian, test

452

453

# Check default configuration

454

default_endian = get_default_endian() # 'big' or 'little'

455

456

# Run comprehensive test suite

457

result = test(verbosity=1)

458

print(f"Tests successful: {result.wasSuccessful()}")

459

print(f"Tests run: {result.testsRun}")

460

461

# Verify all tests passed

462

assert result.wasSuccessful()

463

```

464

465

## Immutable Bitarrays

466

467

```python { .api }

468

class frozenbitarray(bitarray):

469

"""Immutable bitarray that can be used as dictionary key"""

470

471

def __hash__(self) -> int:

472

"""Return hash value for use as dictionary key"""

473

474

def __repr__(self) -> str:

475

"""Return string representation with 'frozen' prefix"""

476

477

# The following methods are disabled and raise TypeError:

478

# append, bytereverse, clear, extend, encode, fill

479

# frombytes, fromfile, insert, invert, pack, pop

480

# remove, reverse, setall, sort, __setitem__, __delitem__

481

# __iadd__, __iand__, __imul__, __ior__, __ixor__

482

# __ilshift__, __irshift__

483

```

484

485

**Usage Examples:**

486

487

```python

488

from bitarray import bitarray, frozenbitarray

489

490

# Create immutable version

491

a = bitarray('10110')

492

frozen = frozenbitarray(a)

493

494

# Use as dictionary key

495

bit_dict = {frozen: 'some value'}

496

lookup = bit_dict[frozenbitarray('10110')] # 'some value'

497

498

# Frozen bitarrays support all read-only operations

499

print(len(frozen)) # 5

500

print(frozen.count()) # 3

501

print(frozen.find('11')) # 2

502

503

# Mutating operations raise TypeError

504

# frozen.append(1) # TypeError: frozenbitarray is immutable

505

```