Logo

Programming-Idioms

  • Pascal
  • Python

Idiom #68 Create a bitset

Create an object x to store n bits (n being potentially large).

from __future__ import division
import math
x = bytearray(int(math.ceil(n / 8.0)))
class BitSet:
    def __init__(self, n):
        self.a = [False] * n
    def __getitem__(self, i):
        return self.a[i]
    def __setitem__(self, k, v):
        self.a[k] = v
    def __str__(self):
        s = ('01'[x] for x in self.a)
        return ''.join(s)
x = BitSet(n)
uses classes;
procedure task;
var 
  x: TBits;
  n: integer;
begin 
  n := $FFF;
  x := TBits.Create(n);
end;

when the set contains more than 256 elements the class TBits must be used
procedure Task;
var
  x: Set Of Byte;
begin
  x:= [2,4,8,16,32,64,256];  
end;

when the set contains less than 256 elements the built-in Set Of construct can be used.
#include <bitset>
std::bitset<n> x;

New implementation...
< >
programming-idioms.org