- Using #define in the construction of an array - 3 Updates
scott@slp53.sl.home (Scott Lurndal): Nov 09 09:12PM >BitsSetTable[k] = number of bits set in the binary expansion of k. >No clue why this works, though. It's neat. >Paul Look at the number of bits required to represent 0-f 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 Note the pattern: 0112 N 1223 N+1 1223 N+1 2334 N+2 look familiar? |
"Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com>: Nov 09 10:52PM +0100 On 09.11.2018 18:12, Paul wrote: > # define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) > B6(0), B6(1), B6(1), B6(2) > }; Others have already explained about the preprocessor. Below is one way to avoid using it for this task in C++. I don't know if it's worth it, though, but it may perhaps bring some insight about the numbers (they're a mystery to me so far). # define B2(n) n, n+1, n+1, n+2 # define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2) # define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) static const unsigned char BitsSetTable256[256] = { B6(0), B6(1), B6(1), B6(2) }; //-------------------------------------------------------------- #include <array> using Byte = unsigned char; template< int level > constexpr auto b( const int n, const int i ) -> int { const int sequence_length = 1 << level; const int subsequence_length = sequence_length/4; const int subseq_i = i/subsequence_length; return b<level-2>( n + subseq_i - (subseq_i >= 2), i%subsequence_length ); } template<> constexpr auto b<2>( const int n, const int i ) -> int { return n + i - (i >= 2); } constexpr auto bits_set_256( const int i ) -> Byte { return b<8>( 0, i ); } //-------------------------------------------------------------- #include <iostream> #include <stdlib.h> auto main() -> int { using namespace std; for( int i = 0; i < 256; ++i ) { const int a = BitsSetTable256[i]; const int b = bits_set_256( i ); if( a != b ) { cout << "At index " << i << ": " << "BitSetTable256 " << a << " != " << "bits_set_256 " << b << endl; return EXIT_FAILURE; } } cout << "Alles in ordnung!" << endl; return EXIT_SUCCESS; } Cheers!, - Alf |
Jorgen Grahn <grahn+nntp@snipabacken.se>: Nov 09 11:22PM On Fri, 2018-11-09, Paul wrote: > Below is part of some code for counting how many bits of an integer are set, > using a lookup table. ... > static const unsigned char BitsSetTable256[256] = ... FWIW, I wouldn't do it like that: it's cryptic, and I suspect it's slow. Lookup tables made more sense in the 1990s, before CPUs became much faster than RAM. /Jorgen -- // Jorgen Grahn <grahn@ Oo o. . . \X/ snipabacken.se> O o . |
You received this digest because you're subscribed to updates for this group. You can change your settings on the group membership page. To unsubscribe from this group and stop receiving emails from it send an email to comp.lang.c+++unsubscribe@googlegroups.com. |
No comments:
Post a Comment