Читаем Thinking In C++. Volume 2: Practical Programming полностью

A bitset provides the most commonly used bitwise operations in an efficient form. However, each bitset is implemented by logically packing bits in an array of integral types (typically unsigned longs, which contain at least 32 bits). In addition, the only conversion from a bitset to a numerical value is to an unsigned long (via the function to_ulong( )).

The following example tests almost all the functionality of the bitset (the missing operations are redundant or trivial). You’ll see the description of each of the bitset outputs to the right of the output so that the bits all line up, and you can compare them to the source values. If you still don’t understand bitwise operations, running this program should help.

//: C07:BitSet.cpp

//{-bor}

// Exercising the bitset class

#include

#include

#include

#include

#include

#include

using namespace std;

const int sz = 32;

typedef bitset BS;

template

bitset randBitset() {

  bitset r(rand());

  for(int i = 0; i < bits/16 - 1; i++) {

    r <<= 16;

    // "OR" together with a new lower 16 bits:

    r |= bitset(rand());

  }

  return r;

}

int main() {

  srand(time(0));

  cout << "sizeof(bitset<16>) = "

    << sizeof(bitset<16>) << endl;

  cout << "sizeof(bitset<32>) = "

    << sizeof(bitset<32>) << endl;

  cout << "sizeof(bitset<48>) = "

    << sizeof(bitset<48>) << endl;

  cout << "sizeof(bitset<64>) = "

    << sizeof(bitset<64>) << endl;

  cout << "sizeof(bitset<65>) = "

    << sizeof(bitset<65>) << endl;

  BS a(randBitset()), b(randBitset());

  // Converting from a bitset:

  unsigned long ul = a.to_ulong();

  cout << a << endl;

  // Converting a string to a bitset:

  string cbits("111011010110111");

Перейти на страницу:

Похожие книги

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

Программирование, программы, базы данных / Программное обеспечение / Книги по IT