C++ Hacks
Back to the main page
Bit twiddling
Various bit twiddling hacks can be found at S. Anderson's
Bit Twiddling Hacks site.
Additional hacks I use in my C++ projects can be found here:
Parallel swapping of odd and even bits of a word
Swap the odd and even bits of a word. Example with 16-bit words:
b15b14b13b12 b11b10b9b8 b7b6b5b4 b3b2b1b0
→
b14b15b12b13 b10b11b8b9 b6b7b4b5 b2b3b0b1
The following function works for 32-bit words
unsigned int swapOddEven( unsigned int v )
{
return ( ( v & 0xAAAAAAAA ) >> 1 ) |
( ( v & 0x55555555 ) << 1 );
}
The first part
( v & 0xAAAAAAAA ) >> 1
selects the odd bits of
v and shifts them to the even positions,
the second part
( v & 0x55555555 ) << 1
selects the even bits of
v and shifts them to the odd positions.
STL
Selective erasing of items from a std::set
Erase all elements of the set
s meeting the
condition:
std::set<...> s;
for( std::set<...>::iterator i = s.begin(); i != s.end(); )
{
if( condition( *i ) )
{
s.erase( i++ );
}
else
{
++i;
}
}
You may alternatively use STLs
remove_if algorithm, but this requires the specification of a condition predicate functor, which is not needed in the above solution.
T to string conversion
A template method to convert any type T to a std::string using an output string stream. The only condition on T is the existence of an output operator for T (
std::ostream& operator<<( std::ostream&, const T& )
#include <sstream>
#include <string>
/* creates a std::string from a value of type T */
template<typename T> std::string toString( const T& value )
{
/* create an output string stream */
std::ostringstream oss;
/* output the value to the stream */
oss << value;
/* return the streams string representation */
return oss.str();
}
You can specialize this function for
std::string parameters to avoid unnecessary conversions:
template<> std::string toString( const std::string& value )
{
/* just return the value. no conversion needed */
return value;
}