|
|
|||
File indexing completed on 2026-04-09 07:49:30
0001 #pragma once 0002 0003 /** 0004 https://stackoverflow.com/questions/1392059/algorithm-to-generate-bit-mask 0005 **/ 0006 0007 #include <climits> 0008 0009 template <typename T> 0010 static constexpr T sbitmask(unsigned n) 0011 { 0012 //return static_cast<T>(-(n != 0)) & (static_cast<T>(-1) >> ((sizeof(T) * CHAR_BIT) - n)); 0013 //return n == 0 ? 0 : (static_cast<T>(-1) >> ((sizeof(T) * CHAR_BIT) - n)); 0014 return n == 0 ? 0 : ( (~static_cast<T>(0)) >> ((sizeof(T) * CHAR_BIT) - n)); 0015 } 0016 0017 /** 0018 sbitmask_ = lambda i:np.uint64(-1) >> np.uint64(64-i) 0019 0020 In [51]: for i in range(64+1):print(" {0:2d} {1:064b} ".format(i, sbitmask_(i))) 0021 0 0000000000000000000000000000000000000000000000000000000000000000 0022 1 0000000000000000000000000000000000000000000000000000000000000001 0023 2 0000000000000000000000000000000000000000000000000000000000000011 0024 3 0000000000000000000000000000000000000000000000000000000000000111 0025 4 0000000000000000000000000000000000000000000000000000000000001111 0026 5 0000000000000000000000000000000000000000000000000000000000011111 0027 6 0000000000000000000000000000000000000000000000000000000000111111 0028 0029 In [61]: "{0:064b}".format( ~sbitmask_(64-8) ) 0030 Out[61]: '1111111100000000000000000000000000000000000000000000000000000000' 0031 0032 In [62]: "{0:064b}".format( ~sbitmask_(64-7) ) 0033 Out[62]: '1111111000000000000000000000000000000000000000000000000000000000' 0034 0035 In [63]: "{0:064b}".format( ~sbitmask_(64-3) ) 0036 Out[63]: '1110000000000000000000000000000000000000000000000000000000000000' 0037 0038 0039 **/ 0040 0041 0042 template <typename T> 0043 static constexpr T sbitmask_0(unsigned n) 0044 { 0045 return static_cast<T>(-(n != 0)) ; 0046 // all bits set, except for n=0 which gives all bits unset 0047 } 0048 0049 template <typename T> 0050 static constexpr T sbitmask_1(unsigned n) 0051 { 0052 return static_cast<T>(-1) >> ((sizeof(T) * CHAR_BIT) - n); 0053 } 0054 0055 template <typename T> 0056 static constexpr T sbitmask_2(unsigned n) 0057 { 0058 return static_cast<T>(-1) ; 0059 } 0060 0061
| [ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
|
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |
|