Logo

Programming-Idioms

  • PHP
  • Python
  • Scheme
  • Pascal
  • JS
  • C++

Idiom #68 Create a bitset

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

#include <bitset>
std::bitset<n> x;
#include <vector>
std::vector<bool> x(n, 0);

This will create a vector of n bits initialized to 0.
$x = new BitSet($n);

Required BitSet PECL Package
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)
from __future__ import division
import math
x = bytearray(int(math.ceil(n / 8.0)))
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.
let x = new Buffer (Math.ceil (n / 8))

Buffers allocate bytes, so we divide n by 8 and take the ceiling of n
using System.Collections;
new BitArray(n);

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