Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a bitset type all bits to 1

Tags:

c++

std-bitset

I know set() function for a already constructed bitset object, but I need a constructed bitset which all bits are 1. The situation is a default function parameter. for example:

void bar(std::bitset<100> flags = X) {
}

what X should be, -1 may works for first 64 bits, but not all.

like image 353
user2729541 Avatar asked Aug 29 '13 14:08

user2729541


People also ask

How do I convert bitset to all bits to 1?

bitset set() function in C++ STL bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1.

How do I know what bit my bitset is?

bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not. Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not. Return Value: The function returns a boolean value.

How do I return a bitset in C++?

The bitset::any() is an inbuilt function in C++ STL which returns True if at least one bit is set in a number. It returns False if all the bits are not set or if the number is zero. Parameter: The function does not accepts any parameter. Return Value: The function returns a boolean value.


2 Answers

std::bitset<100> bs;
bs.set();

Or combine into 1 statement:

std::bitset<100> bs  = std::bitset<100>().set();

In C++11:

auto bs = std::bitset<100>{}.set();

Edit: or better use std::move to avoid copy because set return lvalue reference bitset&:

auto bs = std::move(std::bitset<100>{}.set());

Performance of operator ~, flip() and set():

std::bitset<100> bs;
clock_t t;
t = clock();
for(int i = 0; i < 1000000; i++) {
    bs = std::bitset<100>().set();
}
t = clock() - t;
std::cout << "Using set() cost: " << t << " clicks." << std::endl;

t = clock();
for(int i = 0; i < 1000000; i++) {
    bs = ~std::bitset<100>();
}
t = clock() - t;
std::cout << "Using ~ cost: " << t << " clicks." << std::endl;

t = clock();
for(int i = 0; i < 1000000; i++) {
    bs = std::bitset<100>().flip();
}
t = clock() - t;
std::cout << "Using flip cost: " << t << " clicks." << std::endl;

Output:

Using set() cost: 59 clicks.
Using ~ cost: 104 clicks.
Using flip cost: 75 clicks.

Surprisingly set() is much faster than operator ~ and flip

like image 96
SwiftMango Avatar answered Sep 27 '22 05:09

SwiftMango


You can use std::bitset<100> = std::bitset<100>(std::string(100, '1')) but it's a bit ugly imo

like image 26
Guillaume Avatar answered Sep 28 '22 05:09

Guillaume