Поделиться через


<bitset> Операторов

operator&

Выполняет побитовую операцию AND между двумя битовыми массивами.

template <size_t size>
bitset<size>
operator&(
    const bitset<size>& left,
    const bitset<size>& right);

Параметры

left
Первый из двух битовых массивов, элементы которого должны объединяться с помощью побитовой операции AND.

right
Второй из двух массивов, элементы которого должны объединяться с помощью побитовой операции AND.

Возвращаемое значение

Битовый набор, элементы которого являются результатом AND выполнения операции с соответствующими элементами слева и справа.

Пример

// bitset_and.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>
#include <string>

using namespace std;

int main()
{
   bitset<4> b1 ( string("0101") );
   bitset<4> b2 ( string("0011") );
   bitset<4> b3 = b1 & b2;
   cout << "bitset 1: " << b1 << endl;
   cout << "bitset 2: " << b2 << endl;
   cout << "bitset 3: " << b3 << endl;
}
bitset 1: 0101
bitset 2: 0011
bitset 3: 0001

operator<<

Вставляет текстовое представление битовой последовательности в поток вывода.

template <class CharType, class Traits, size_t N>
basic_ostream<CharType, Traits>& operator<<(
    basic_ostream<CharType, Traits>& ostr,
    const bitset<N>& right);

Параметры

right
Объект набора типов<N> , который должен быть вставлен в выходной поток в виде строки.

Возвращаемое значение

Текстовое представление битовой последовательности в ostr.

Замечания

Перегрузки operator<<функции шаблона позволяют записывать битовый набор без первого преобразования его в строку. Шаблонная функция фактически выполняется.

ostr << right.to_string<CharType, Traits, allocator<CharType>>()

Пример

// bitset_op_insert.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>
#include <string>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 9 );

   // bitset inserted into output stream directly
   cout << "The ordered set of bits in the bitset<5> b1(9)"
        << "\n can be output with the overloaded << as: ( "
        << b1 << " )" << endl;

   // Compare converting bitset to a string before
   // inserting it into the output stream
   string s1;
   s1 =  b1.template to_string<char,
      char_traits<char>, allocator<char> >( );
   cout << "The string returned from the bitset b1"
        << "\n by the member function to_string( ) is: "
        << s1 << "." << endl;
}

operator>>

Считывает строку битовых символов в битовый массив.

template <class CharType, class Traits, size_t Bits>
basic_istream<CharType, Traits>& operator>> (
    basic_istream<CharType, Traits>& i_str,
    bitset<N>& right);

Параметры

i_str
Строка, которая вводится во входной поток для вставки в битовый массив.

right
Битовый массив, получающий биты из входного потока.

Возвращаемое значение

Функция шаблона возвращает строку i_str.

Замечания

Функция шаблона перегружена operator>> для хранения в битовом наборе справа от значения bitset(str), где str объект типа basic_string< CharType, Traits, allocator< CharType > >& извлечен из i_str.

Функция шаблона извлекает элементы из i_str и вставляет их в набор битов, пока:

  • все битовые элементы будут извлечены из входного потока и сохранены в битовый массив;

  • битовый массив заполнится битами из входного потока;

  • встретится входной элемент, не являющийся ни 0, ни 1.

Пример

#include <bitset>
#include <iostream>
#include <string>

using namespace std;
int main()
{
   bitset<5> b1;
   cout << "Enter string of (0 or 1) bits for input into bitset<5>.\n"
        << "Try bit string of length less than or equal to 5,\n"
        << " (for example: 10110): ";
   cin >>  b1;

   cout << "The ordered set of bits entered from the "
        << "keyboard\n has been input into bitset<5> b1 as: ( "
        << b1 << " )" << endl;

   // Truncation due to longer string of bits than length of bitset
   bitset<2> b3;
   cout << "Enter string of bits (0 or 1) for input into bitset<2>.\n"
        << " Try bit string of length greater than 2,\n"
        << " (for example: 1011): ";
   cin >>  b3;

   cout << "The ordered set of bits entered from the "
        << "keyboard\n has been input into bitset<2> b3 as: ( "
        << b3 << " )" << endl;

   // Flushing the input stream
   char buf[100];
   cin.getline(&buf[0], 99);

   // Truncation with non-bit value
   bitset<5> b2;
   cout << "Enter a string for input into  bitset<5>.\n"
        << " that contains a character than is NOT a 0 or a 1,\n "
        << " (for example: 10k01): ";
   cin >>  b2;

   cout << "The string entered from the keyboard\n"
        << " has been input into bitset<5> b2 as: ( "
        << b2 << " )" << endl;
}

operator^

Выполняет побитовую операцию EXCLUSIVE-OR между двумя битовыми массивами.

template <size_t size>
bitset<size>
operator^(
    const bitset<size>& left,
    const bitset<size>& right);

Параметры

left
Первый из двух битовых массивов, элементы которого должны объединяться с помощью побитовой операции EXCLUSIVE-OR.

right
Второй из двух массивов, элементы которого должны объединяться с помощью побитовой операции EXCLUSIVE-OR.

Возвращаемое значение

Битовый набор, элементы которого являются результатом EXCLUSIVE-OR выполнения операции с соответствующими элементами слева и справа.

Пример

// bitset_xor.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>
#include <string>

using namespace std;

int main()
{
   bitset<4> b1 ( string("0101") );
   bitset<4> b2 ( string("0011") );
   bitset<4> b3 = b1 ^ b2;
   cout << "bitset 1: " << b1 << endl;
   cout << "bitset 2: " << b2 << endl;
   cout << "bitset 3: " << b3 << endl;
}
bitset 1: 0101
bitset 2: 0011
bitset 3: 0110

operator|

Выполняет битовую или между двумя bitset объектами.

template <size_t size>
bitset<size>
operator|(
    const bitset<size>& left,
    const bitset<size>& right);

Параметры

left
Первый из двух битовых массивов, элементы которого должны объединяться с помощью побитовой операции OR.

right
Второй из двух массивов, элементы которого должны объединяться с помощью побитовой операции OR.

Возвращаемое значение

Битовый набор, элементы которого являются результатом OR выполнения операции с соответствующими элементами слева и справа.

Пример

// bitset_or.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>
#include <string>

using namespace std;

int main()
{
   bitset<4> b1 ( string("0101") );
   bitset<4> b2 ( string("0011") );
   bitset<4> b3 = b1 | b2;
   cout << "bitset 1: " << b1 << endl;
   cout << "bitset 2: " << b2 << endl;
   cout << "bitset 3: " << b3 << endl;
}
bitset 1: 0101
bitset 2: 0011
bitset 3: 0111