Passing bitset to function

M

Michal Wyrebski

Hello,

I was thinking how is the fastest and the best way of passing bitset
variable to some function.
Only one method came to my mind. It's about passing converted value:

#v+
void func(unsigned long UL) {
bitset<8> B(UL);
cout << "B: " << B << endl;
}

int main() {
bitset<8> H('A');
func(H.to_ulong() );
return 0;
}
#v-

Of course converting to string is also possible.

OK this just works. But what if I want to pass some number of bits and
func() had no information about its number?
It's impossible to write like that:

#v+
void func(unsigned long UL, const int len) {
bitset<len> B(UL);
(...)
#v-

g++ says: `len' cannot appear in a constant-expression

How, then, pass some number of bits, that function could create
stucture (bitset) of required length?
Any ideas?


Michal
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

I was thinking how is the fastest and the best way of passing bitset
variable to some function.

Best way is probably passing by reference. Very common... To determine
whether it's the fastest, you will need to test different approaches in your
program.

#include <iostream>
#include <bitset>

typedef std::bitset<8> EightBits;

void func(EightBits const & bits)
{
std::cout << bits << '\n';
}

int main()
{
EightBits h('A');
func(h);
}

Ali
 
J

John Harrison

Michal said:
Hello,

I was thinking how is the fastest and the best way of passing bitset
variable to some function.
Only one method came to my mind. It's about passing converted value:

#v+
void func(unsigned long UL) {
bitset<8> B(UL);
cout << "B: " << B << endl;
}

int main() {
bitset<8> H('A');
func(H.to_ulong() );
return 0;
}
#v-

Of course converting to string is also possible.

OK this just works. But what if I want to pass some number of bits and
func() had no information about its number?
It's impossible to write like that:

#v+
void func(unsigned long UL, const int len) {
bitset<len> B(UL);
(...)
#v-

g++ says: `len' cannot appear in a constant-expression

How, then, pass some number of bits, that function could create
stucture (bitset) of required length?

Cannot be done, because bitset is a template the size must be a compile
time constant.
Any ideas?

If you need a set of bits whose size is not determined at compile time
then vector<bool>, vector<char> and string are all possiblities.
vector<bool> is specialised to take the minimum possible space (i.e.
several bits are stored as a single byte).

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,744
Latest member
CortneyMcK

Latest Threads

Top