Re: Bitset Replacement
Alex Buell wrote:
On 12 Jun 2006 07:51:52 -0700, I waved a wand and this message
magically appeared from woessner@gmail.com:
I'm using a C++ compiler on a DSP that doesn't provide the bitset
class. Can anyone suggest a replacement for it? I've written a lot
of code that uses the bitset class (before I knew about the...
inadequacies of the compiler), so it needs to have approximately the
same interface.
You're in luck, here's something you might can use. I hereby place this
code into the public domain with this post.
#ifndef __BINARY__
#define __BINARY__
Uhh, you *still* can't use names starting with double underscores, as
they are reserved for the implementation. Yes, it might not cause a
problem on your system, but think about all the other folks who might
use your library.
#include <iostream>
#include <string>
#include <limits>
#include <assert.h>
If he doesn't have <bitset>, I'd guess he lacks the other standard
headers, too. BTW, you c/should use <cassert> instead of <assert.h>.
class binary
{
public:
template <typename T>
binary(const T& n)
{
const unsigned int bits =
std::numeric_limits<T>::digits; for (unsigned int i = 0; i < bits; i++)
digits.insert(digits.begin(), (n & (1 << i)) ?
'1' : '0');
To reiterate from the last time you posted this code: you should use
reserve() here to prevent reallocation inefficiencies.
assert(digits.size() == bits);
}
const bool test(const unsigned int n) const
{
assert(n < digits.size() + 1);
return (digits[n - 1] == '1') ? true : false;
}
void set(const unsigned int n)
{
assert(n < digits.size() + 1);
digits[n - 1] = '1';
}
friend std::ostream& operator<<(std::ostream& stream, const
binary& bin) {
return stream << bin.digits;
}
private:
std::string digits;
Using a std::string is perhaps efficient for printing, but I'm guessing
the code the OP has written is more concerned with bit-twiddling and so
forth where this wouldn't likely be efficient since he'll need the
value back as a number eventually. Moreover, DSPs generally don't excel
at string handling, and so that functionality is often put elsewhere in
the system.
};
#endif // __BINARY__
Cheers! --M