-
Notifications
You must be signed in to change notification settings - Fork 96
/
EABitTricks.h
1566 lines (1364 loc) · 49.6 KB
/
EABitTricks.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This is a list of C/C++ bit manipulation tricks. For example, it is
// well-known that (x * 2) can be also accomplished with (x << 1).
// And while this example may not be useful in practice, there are many
// more such tricks which have real use, particularly for speeding up code.
//
// Notes:
// * Twos-complement integer storage is assumed. Nearly all modern
// processors use twos-complement storage.
// * Some tricks assume that right shifts of signed values preserve
// the sign. While nearly all modern processors and C/C++ compilers
// support this, some primitive processors don't. By preserving sign,
// we mean that signed binary (10000000 >> 1) gives (11000000).
// * Only 'tricky' efficient solutions are provided. Obvious brute force loops
// to do useful things aren't included. We attempt to use branchless and
// loopless logic where possible.
// * We don't cover magic number tricks for simplifying multiplication and
// division by constants. For example (x * 17) can also be quickly accomplished
// with ((x << 4) + x). Optimized integer multiplication and division tricks
// such as this is something for a separate library.
// * We don't cover floating point tricks. That is something for a separate library.
// * Implementations here are written as standalone functions for readability.
// However, the user may find that it's better in some cases to copy the implementation
// to a macro or to simply copy the implementation directly inline into source
// code. EABitTricks is meant to be a reference for copy and paste as much as
// it is meant to be used as-is.
// * Many of these functions are templated instead of taking a given integer
// type such as uint32_t. The reason for this is that we want 64 bit support
// and that can be had automatically in most cases by the use of templates. The
// generated code will be exactly as fast as the case when templates are not used.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef EASTDC_EABITTRICKS_H
#define EASTDC_EABITTRICKS_H
#include <EAStdC/internal/Config.h>
#include <EABase/eabase.h>
#include <limits.h>
#if defined(EA_COMPILER_MSVC) && (defined(EA_PROCESSOR_X86) || defined(EA_PROCESSOR_X86_64))
// We can use assembly intrinsics for some of these functions.
EA_DISABLE_ALL_VC_WARNINGS()
#include <math.h> // VS2008 has an acknowledged bug that requires math.h (and possibly also string.h) to be #included before intrin.h.
#include <intrin.h>
EA_RESTORE_ALL_VC_WARNINGS()
#pragma intrinsic(_BitScanForward)
#pragma intrinsic(_BitScanReverse)
#if defined(EA_PROCESSOR_X86_64)
#pragma intrinsic(_BitScanForward64)
#pragma intrinsic(_BitScanReverse64)
#endif
#elif (defined(EA_COMPILER_GNUC) || defined(EA_COMPILER_CLANG)) && (defined(EA_PROCESSOR_X86) || defined(EA_PROCESSOR_X86_64))
#include <x86intrin.h>
#endif
EA_DISABLE_VC_WARNING(6326 4146) // C6326: Potential comparison of a constant with another constant
// C4146: unary minus operator applied to unsigned type, result still unsigned
namespace EA
{
namespace StdC
{
namespace helper
{
///////////////////////////////////////////////////////////////////////
// is_signed
///////////////////////////////////////////////////////////////////////
struct false_type { static const bool value = false; };
struct true_type { static const bool value = true; };
template <typename T> struct is_signed : public false_type{};
template <> struct is_signed<signed char> : public true_type{};
template <> struct is_signed<const signed char> : public true_type{};
template <> struct is_signed<signed short> : public true_type{};
template <> struct is_signed<const signed short> : public true_type{};
template <> struct is_signed<signed int> : public true_type{};
template <> struct is_signed<const signed int> : public true_type{};
template <> struct is_signed<signed long> : public true_type{};
template <> struct is_signed<const signed long> : public true_type{};
template <> struct is_signed<signed long long> : public true_type{};
template <> struct is_signed<const signed long long> : public true_type{};
#if (CHAR_MAX == SCHAR_MAX)
template <> struct is_signed<char> : public true_type{};
template <> struct is_signed<const char> : public true_type{};
#endif
#ifndef EA_WCHAR_T_NON_NATIVE // If wchar_t is a native type instead of simply a define to an existing type...
#if defined(__WCHAR_MAX__) && ((__WCHAR_MAX__ == 2147483647) || (__WCHAR_MAX__ == 32767)) // GCC defines __WCHAR_MAX__ for most platforms.
template <> struct is_signed<wchar_t> : public true_type{};
template <> struct is_signed<const wchar_t> : public true_type{};
#endif
#endif
#define bt_is_signed helper::is_signed<T>::value
//////////////////////////////////////////////
// add_signed
//////////////////////////////////////////////
template<typename T>
struct add_signed
{ typedef T type; };
template<>
struct add_signed<unsigned char>
{ typedef signed char type; };
#if (defined(CHAR_MAX) && defined(UCHAR_MAX) && (CHAR_MAX == UCHAR_MAX)) // If char is unsigned (which is usually not the case)...
template<>
struct add_signed<char>
{ typedef signed char type; };
#endif
template<>
struct add_signed<unsigned short>
{ typedef short type; };
template<>
struct add_signed<unsigned int>
{ typedef int type; };
template<>
struct add_signed<unsigned long>
{ typedef long type; };
template<>
struct add_signed<unsigned long long>
{ typedef long long type; };
#ifndef EA_WCHAR_T_NON_NATIVE // If wchar_t is a native type instead of simply a define to an existing type...
#if (defined(__WCHAR_MAX__) && (__WCHAR_MAX__ == 4294967295U)) // If wchar_t is a 32 bit unsigned value...
template<>
struct add_signed<wchar_t>
{ typedef int32_t type; };
#elif (defined(__WCHAR_MAX__) && (__WCHAR_MAX__ == 65535)) // If wchar_t is a 16 bit unsigned value...
template<>
struct add_signed<wchar_t>
{ typedef int16_t type; };
#endif
#endif
#define bt_signed typename helper::add_signed<T>::type // Must be used as part of a cast, as in (bt_signed) or static_cast<bt_signed>()
}
////////////////////////////////////////////////////////////////////////////
// Bit manipulation
////////////////////////////////////////////////////////////////////////////
/// TurnOffLowestBit
/// How to turn off the lowest 1 bit in an integer.
/// Returns 0 for an input of 0.
/// Works with signed and unsigned integers.
/// Example:
/// 01011000 -> 01010000
template <typename T>
inline T TurnOffLowestBit(T x){
return (T)(x & (x - 1));
}
/// IsolateLowestBit
/// How to isolate the lowest 1 bit.
/// Returns 0 for an input of 0.
/// Example:
/// 01011000 -> 00001000
template <typename T>
inline T IsolateLowestBit(T x){
return (T)(x & (0 - x));
}
/// IsolateLowest0Bit
/// How to isolate the lowest 0 bit.
/// Returns 0 for an input of all bits set.
/// Example:
/// 10100111 -> 00001000
template <typename T>
inline T IsolateLowest0Bit(T x){
return (T)(~x & (x + 1));
}
/// GetTrailing0Bits
/// How to produce a mask of all low zeroes.
/// Returns 0 for an input of all bits set.
/// Example:
/// 01011000 -> 00000111
template <typename T>
inline T GetTrailing0Bits(T x){
return (T)(~x & (x - 1));
}
/// GetTrailing1And0Bits
/// How to produce a mask of lowest 1 bit and all lower zeroes.
/// Returns all bits set for an input of 0.
/// Returns 1 for an input of all bits set.
/// Example:
/// 01011000 -> 00001111
template <typename T>
inline T GetTrailing1And0Bits(T x){
return (T)(x ^ (x - 1));
}
/// PropogateLowestBitDownward
/// How to propogate the lowest 1 bit downward.
/// Returns all bits set for an input of 0.
/// Example:
/// 01011000 -> 01011111
template <typename T>
inline T PropogateLowestBitDownward(T x){
return (T)(x | (x - 1));
}
/// TurnOffLowestContiguousBits
/// How to turn off the lowest contiguous string of 1 bits.
/// Returns 0 for an input of 0.
/// Returns 0 for an input of all bits set.
/// Example:
/// 01011000 -> 01000000
template <typename T>
inline T TurnOffLowestContiguousBits(T x){
return (T)(((x | (x - 1)) + 1) & x);
}
/// TurnOnLowest0Bit
/// How to turn off the lowest 0 bit in an integer.
/// Returns all bits set for an input of all bits set.
/// Example:
/// 10100111 -> 10101111
template <typename T>
inline T TurnOnLowest0Bit(T x){
return (T)(x | (x + 1));
}
/// GetNextWithEqualBitCount
/// How to get the next higher integer with the same number of bits set.
/// This function is supposed (claim by original author) to be able to
/// wrap around and continue properly, but testing indicates otherwise.
/// Do not call this with x = 0; as that causes a divide by 0.
/// Doesn't work for an input of all bits set.
/// Do not assign the result of this to a type of less size than the input argument.
/// This function has certain real-world applications.
/// This function has been called 'snoob' by some.
/// Example:
/// 01010110 -> 01011001
template <typename T>
inline T GetNextWithEqualBitCount(T x){
T smallest, ripple, ones;
smallest = x & -(bt_signed)x;
ripple = x + smallest;
ones = x ^ ripple;
ones = (ones >> 2) / smallest;
return ripple | ones;
}
/// IsolateSingleBits
/// How to isolate single bits in an integer.
/// Example:
/// 10101011 -> 10101000
template <typename T>
inline T IsolateSingleBits(T x){
return x & ~((x << 1) | (x >> 1));
}
template <typename T>
inline T IsolateSingle0Bits(T x){
return IsolateSingleBits(~x);
}
template <typename T>
inline T IsolateSingle0And1Bits(T x){
return (x ^ (x << 1)) & (x ^ (x >> 1));
}
/// ShiftRightSigned
/// How to do a signed right shift portably.
/// Some platform/compiler combinations don't support sign extension
/// with right shifts of signed values. The C language standard doesn't
/// guarantee such functionality. Most advanced CPUs and nearly all C
/// compilers support this. Weak embedded processors may possibly not.
/// Example:
/// 10000000 - by 2-> 11100000
/// 00000000 - by 2-> 00000000
inline int32_t ShiftRightSigned(int32_t x, uint32_t n){
return int32_t((((uint32_t)x + UINT32_C(0x80000000)) >> n) - (UINT32_C(0x80000000) >> n));
}
inline int64_t ShiftRightSigned(int64_t x, uint64_t n){
return int64_t((((uint64_t)x + UINT64_C(0x8000000000000000)) >> n) - (UINT64_C(0x8000000000000000) >> n));
}
/// CountTrailing0Bits
/// How to count the number of trailing zeroes in an unsigned 32 bit integer.
/// Example:
/// ...10101000 -> 3
/// ...11111111 -> 0
/// ...00000000 -> 32
inline int CountTrailing0Bits(uint32_t x){
#if defined(EA_COMPILER_MSVC) && (defined(EA_PROCESSOR_X86) || defined(EA_PROCESSOR_X86_64))
// This has been benchmarked as significantly faster than the generic code below.
unsigned char isNonZero;
unsigned long index;
isNonZero = _BitScanForward(&index, x);
return isNonZero ? (int)index : 32;
#elif defined(EA_COMPILER_GNUC) && !defined(EA_COMPILER_EDG)
if(x)
return __builtin_ctz(x);
return 32;
#else
if(x){
int n = 1;
if((x & 0x0000FFFF) == 0) {n += 16; x >>= 16;}
if((x & 0x000000FF) == 0) {n += 8; x >>= 8;}
if((x & 0x0000000F) == 0) {n += 4; x >>= 4;}
if((x & 0x00000003) == 0) {n += 2; x >>= 2;}
return n - int(x & 1);
}
return 32;
#endif
}
/// CountTrailing0Bits
/// How to count the number of trailing zeroes in an unsigned 64 bit integer.
/// Example:
/// ...10101000 -> 3
/// ...11111111 -> 0
/// ...00000000 -> 64
inline int CountTrailing0Bits(uint64_t x){
#if defined(EA_COMPILER_MSVC) && defined(EA_PROCESSOR_X86_64)
// This has been benchmarked as significantly faster than the generic code below.
unsigned char isNonZero;
unsigned long index;
isNonZero = _BitScanForward64(&index, x);
return isNonZero ? (int)index : 64;
#elif defined(EA_COMPILER_GNUC) && !defined(EA_COMPILER_EDG)
if(x)
return __builtin_ctzll(x);
return 64;
#else
if(x){
int n = 1;
if((x & 0xFFFFFFFF) == 0) { n += 32; x >>= 32; }
if((x & 0x0000FFFF) == 0) { n += 16; x >>= 16; }
if((x & 0x000000FF) == 0) { n += 8; x >>= 8; }
if((x & 0x0000000F) == 0) { n += 4; x >>= 4; }
if((x & 0x00000003) == 0) { n += 2; x >>= 2; }
return n - (int)(unsigned)(x & 1);
}
return 64;
#endif
}
/// CountLeading0Bits
/// How to count the number of leading zeroes in an unsigned integer.
/// Example:
/// ..00000000 -> 32
/// 00110111 -> 2
/// 11111111 -> 0
///
inline int CountLeading0Bits(uint32_t x){
#if defined(EA_COMPILER_MSVC) && (defined(EA_PROCESSOR_X86) || defined(EA_PROCESSOR_X86_64))
// This has been benchmarked as significantly faster than the generic code below.
unsigned char isNonZero;
unsigned long index;
isNonZero = _BitScanReverse(&index, x);
return isNonZero ? (31 - (int)index) : 32;
#elif defined(EA_COMPILER_GNUC) && !defined(EA_COMPILER_EDG)
if(x)
return __builtin_clz(x);
return 32;
#else
/// This implementation isn't highly compact, but would likely be
/// faster than a brute force solution.
/// x86 function which is claimed to be faster:
/// double ff = (double)(v|1);
/// return ((*(1+(unsigned long *)&ff))>>20)-1023;
if(x){
int n = 0;
if(x <= 0x0000FFFF) { n += 16; x <<= 16; }
if(x <= 0x00FFFFFF) { n += 8; x <<= 8; }
if(x <= 0x0FFFFFFF) { n += 4; x <<= 4; }
if(x <= 0x3FFFFFFF) { n += 2; x <<= 2; }
if(x <= 0x7FFFFFFF) { n += 1; }
return n;
}
return 32;
#endif
}
/// CountLeading0Bits
/// How to count the number of leading zeroes in an unsigned integer.
/// Example:
/// ..00000000 -> 64
/// ..00110111 -> 2
/// ..11111111 -> 0
///
inline int CountLeading0Bits(uint64_t x){
#if defined(EA_COMPILER_MSVC) && defined(EA_PROCESSOR_X86_64)
// This has been benchmarked as significantly faster than the generic code below.
unsigned char isNonZero;
unsigned long index;
isNonZero = _BitScanReverse64(&index, x);
return isNonZero ? (63 - (int)index) : 64;
#elif defined(EA_COMPILER_GNUC) && !defined(EA_COMPILER_EDG)
if(x)
return __builtin_clzll(x);
return 64;
#else
if(x){ // We use a slightly different algorithm than the 32 bit version above because this version avoids slow large 64 bit constants, especially on RISC processors.
int n = 0;
if(x & UINT64_C(0xFFFFFFFF00000000)) { n += 32; x >>= 32; }
if(x & 0xFFFF0000) { n += 16; x >>= 16; }
if(x & 0xFFFFFF00) { n += 8; x >>= 8; }
if(x & 0xFFFFFFF0) { n += 4; x >>= 4; }
if(x & 0xFFFFFFFC) { n += 2; x >>= 2; }
if(x & 0xFFFFFFFE) { n += 1; }
return 63 - n;
}
return 64;
#endif
}
/// CountBits
/// How to count the number of bits in an unsigned integer.
/// There are multiple variations of this function available,
/// each tuned to the expected bit counts and locations.
/// The version presented here has a large number of logical
/// operations but has no looping or branching.
/// This implementation is taken from the AMD x86 optimization guide.
/// Example:
/// 11001010 -> 4
inline int CountBits(uint32_t x) // Branchless version
{
#if defined(EASTDC_SSE_POPCNT)
return _mm_popcnt_u32(x);
#else
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
return (int)((x * 0x01010101) >> 24);
#endif
}
inline int CountBits64(uint64_t x) // Branchless version
{
#if defined(EASTDC_SSE_POPCNT) && defined(EA_PROCESSOR_X86_64)
return (int)_mm_popcnt_u64(x);
#else
#if (EA_PLATFORM_WORD_SIZE < 8)
return CountBits((uint32_t)(x >> 32)) + CountBits((uint32_t)x);
#else
x = x - ((x >> 1) & UINT64_C(0x5555555555555555));
x = (x & UINT64_C(0x3333333333333333)) + ((x >> 2) & UINT64_C(0x3333333333333333));
x = (x + (x >> 4)) & UINT64_C(0x0F0F0F0F0F0F0F0F);
return (int)((x * UINT64_C(0x0101010101010101)) >> 56);
#endif
#endif
}
/// RotateLeft
/// How to rotate an integer left.
/// Bit rotations can often be accomplished with inline assembly
/// that uses the processor's native bit rotation capabilities.
/// Example:
/// 11110000 -> left 2 -> 11000011
inline uint32_t RotateLeft(uint32_t x, uint32_t n){
return (uint32_t)((x << n) | (x >> (32 - n)));
}
inline uint64_t RotateLeft(uint64_t x, uint64_t n){
return (uint64_t)((x << n) | (x >> (64 - n)));
}
inline uint32_t RotateRight(uint32_t x, uint32_t n){
return (uint32_t)((x >> n) | (x << (32 - n)));
}
inline uint64_t RotateRight(uint64_t x, uint64_t n){
return (uint64_t)((x >> n) | (x << (64 - n)));
}
/// ReverseBits
/// How to reverse the bits in an integer.
/// There are other mechansims for accomplishing this.
/// The version presented here has no branches, looping, nor table lookups.
/// Table lookups are the fastest when done on large amounts of data, but slower
/// when just done once due to the initial lookup cost.
/// Some ARM results: http://corner.squareup.com/2013/07/reversing-bits-on-arm.html
/// http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c
/// Example:
/// 11100001 -> 10000111
inline uint32_t ReverseBits(uint32_t x){
x = ((x & 0x55555555) << 1) | ((x >> 1) & 0x55555555);
x = ((x & 0x33333333) << 2) | ((x >> 2) & 0x33333333);
x = ((x & 0x0F0F0F0F) << 4) | ((x >> 4) & 0x0F0F0F0F);
x = (x << 24) | ((x & 0xFF00) << 8) | ((x >> 8) & 0xFF00) | (x >> 24);
return x;
}
// This is surely not the fastest way to do this, and is here for completeness only.
// To do: Make a better version of this.
inline uint64_t ReverseBits(uint64_t x){
uint32_t x1 = (uint32_t)(x & 0xffffffff);
uint32_t x2 = (uint32_t)(x >> 32);
return ((uint64_t)ReverseBits(x1) << 32) | ReverseBits(x2);
}
/// IsolateHighestBit
/// How to isolate the highest 1 bit.
/// Returns 0 for an input of 0.
/// Example:
/// 01000100 -> 01000000
/// 00000000 -> 00000000
inline uint32_t IsolateHighestBit(uint32_t x){
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
inline uint64_t IsolateHighestBit(uint64_t x){
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return x ^ (x >> 1);
}
inline uint32_t IsolateHighest0Bit(uint32_t x){
return IsolateHighestBit(~x);
}
inline uint64_t IsolateHighest0Bit(uint64_t x){
return IsolateHighestBit(~x);
}
/// PropogateHighestBitDownward
/// How to set all bits from the highest 1 bit downward.
/// Returns 0 for an input of 0.
/// Example:
/// 01001000 -> 01111111
/// 00000000 -> 00000000
inline uint32_t PropogateHighestBitDownward(uint32_t x){
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return x;
}
inline uint64_t PropogateHighestBitDownward(uint64_t x){
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
x |= (x >> 32);
return x;
}
/// GetHighestContiguous0Bits
/// How to set the highest contiguous 0 bits.
/// Returns 0 for an input of all bits set.
/// Example:
/// 00011001 -> 11100000
/// 11111111 -> 00000000
inline uint32_t GetHighestContiguous0Bits(uint32_t x){
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return ~x;
}
inline uint64_t GetHighestContiguous0Bits(uint64_t x){
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
x |= (x >> 32);
return ~x;
}
/// GetBitwiseEquivalence
/// How to calculate bitwise equivalence.
/// Bitwise equivalence is the opposite of xor. It sets all bits that
/// are the same to 1, whereas xor sets all bits that are different to 1.
/// Thus, you can simply use ~ to get bitwise equivalence from xor.
/// Example:
/// 11001100, 11110000 -> 11000011
template <typename T>
inline T GetBitwiseEquivalence(T x, T y){
return (T)(~(x ^ y));
}
/// AreLessThan2BitsSet
/// How to tell if at least two bits are set in an integer.
/// Example:
/// 00001000 -> true
/// 01001110 -> false
template <typename T>
inline bool AreLessThan2BitsSet(T x){
return (x & (x - 1)) == 0;
}
#if defined(EASTDC_SSE_POPCNT)
template <>
inline bool AreLessThan2BitsSet<uint32_t>(uint32_t x){
uint32_t rv = (uint32_t)_mm_popcnt_u32(x);
return (rv < 2);
}
#if defined(EA_PROCESSOR_X86_64)
template <>
inline bool AreLessThan2BitsSet<uint64_t>(uint64_t x){
uint64_t rv = (uint64_t)_mm_popcnt_u64(x);
return (rv < 2);
}
#endif
#endif
/// GetHighestBit
/// How to refer to the high bit of any integer data type where the
/// data type size is not known.
/// There are cases where you may want to refer to the higest bit in
/// an integer in a portable way. If you can't know the size of the
/// destination platform's int type, you can use this to refer to such a bit.
/// Example:
/// GetHighestBit(uint32_t(0)) -> 0x80000000
/// GetHighestBit(uint16_t(0)) -> 0x8000
template <typename T>
inline T GetHighestBit(T /*t*/){
return (T)((T)1 << (T)((sizeof(T) * 8) - 1));
}
////////////////////////////////////////////////////////////////////////////
// Alignment / Power of 2
////////////////////////////////////////////////////////////////////////////
/// IsPowerOf2
/// How to tell if an unsigned integer is a power of 2.
/// Works with unsigned integers only.
/// Returns true for x == 0.
/// Example:
/// 01000010 (66) -> false
/// 00001100 (12) -> false
/// 00000100 (4) -> true
/// 00000000 (0) -> true
template <typename T>
inline bool IsPowerOf2(T x){
return (x & (x - 1)) == 0;
}
#if defined(EASTDC_SSE_POPCNT)
template <>
inline bool IsPowerOf2<uint32_t>(uint32_t x){
uint32_t rv = (uint32_t)_mm_popcnt_u32(x);
return (rv < 2);
}
#if defined(EA_PROCESSOR_X86_64)
template <>
inline bool IsPowerOf2<uint64_t>(uint64_t x){
uint64_t rv = (uint64_t)_mm_popcnt_u64(x);
return (rv < 2);
}
#endif
#endif
/// RoundUpToPowerOf2
/// Rounds an integer up to the nearest power of 2.
/// Returns 16 for x == 16, 32 for x == 32, etc.
/// Returns 0 for x == 0.
/// Example:
/// 01000010 (66) -> 10000000 (128)
/// 00001100 (12) -> 00010000 (16)
/// 00000100 (4) -> 00000100 (4)
/// 00000000 (0) -> 00000000 (0)
inline uint32_t RoundUpToPowerOf2(uint32_t x){
--x;
x |= (x >> 16);
x |= (x >> 8);
x |= (x >> 4);
x |= (x >> 2);
x |= (x >> 1);
return ++x;
}
inline uint64_t RoundUpToPowerOf2(uint64_t x){
--x;
x |= (x >> 32);
x |= (x >> 16);
x |= (x >> 8);
x |= (x >> 4);
x |= (x >> 2);
x |= (x >> 1);
return ++x;
}
/// IsPowerOf2Multiple
/// How to tell if an unsigned integer is a multiple of some specific power of 2.
/// Template constant n is required to be a power of 2.
/// Works with an input unsigned integers only. 'k' must be an even power of 2, such as 1, 2, 4, 8, etc.
/// Returns true for x == 0.
/// Example:
/// IsPowerOf2Multiple<4>(3) -> false
/// IsPowerOf2Multiple<16>(32) -> true
///
template <typename T, int n>
inline bool IsPowerOf2Multiple(T x){
return (x & (n - 1)) == 0;
}
// *** The following is deprecated, as it doesn't use "power of 2" in its name ***
template <typename T, int n>
inline bool IsMultipleOf(T x){
return (x & (n - 1)) == 0;
}
/// IsPowerOf2Minus1
/// How to tell if an unsigned integer is of the form 2n-1 (e.g. 0x0fff, 0x000fffff).
/// Returns true for an input of 0.
/// Example:
/// 00001111 (15) -> true
/// 00001011 (11) -> false
/// 00000000 (0) -> true
template <typename T>
inline bool IsPowerOf2Minus1(T x){
return (x & (x + 1)) == 0;
}
/// CrossesPowerOf2
/// How to detect any power of two crossing between two integers.
/// Useful for telling if an increasing value is about to go over a power of two boundary.
/// Example:
/// 4, 5, 8 -> false
/// 5, 9, 8 -> true
template <typename T>
inline bool CrossesPowerOf2(T x, T y, T n){
return (n - (x & (n - 1))) < (y - x);
}
/// CrossesPowerOf2
/// How to detect a specific power of two crossing between two integers.
/// Template parameter n must be an even power of 2, such as 1, 2, 4, 8, 16, etc.
/// Example:
/// CrossesPowerOf2<8>(3, 5) -> false
/// CrossesPowerOf2<8>(7, 30) -> true
template <typename T, int n>
inline bool CrossesPowerOf2(T x, T y){
return (n - (x & (n - 1))) < (y - x);
}
/////////////////////////////////////////////////////////////////////////////////
// GetHighestBitPowerOf2 template
//
// There is a templated compile-time constant version of GetHighestBitPowerOf2
// but it is called Log2Uint32 / Log2Int32 / Log2Uint64 / Log2Int64. See below
// for that template definition.
/////////////////////////////////////////////////////////////////////////////////
/// GetHighestBitPowerOf2 (a.k.a. GetHighestBitIndex)
/// How to detect the power of 2 of the highest bit set in a uint32_t.
/// The power of 2 is the same as the bit index, so this could also be
/// called GetHighestBitIndex.
/// Returns 0 for an input of 0.
/// Returns a value in the range of [0, 31]
/// Example:
/// GetHighestBitPowerOf2(0) -> 0
/// GetHighestBitPowerOf2(1) -> 0
/// GetHighestBitPowerOf2(2) -> 1
/// GetHighestBitPowerOf2(3) -> 1
/// GetHighestBitPowerOf2(4) -> 2
/// GetHighestBitPowerOf2(7) -> 2
/// GetHighestBitPowerOf2(8) -> 3
inline uint32_t GetHighestBitPowerOf2(uint32_t x){
uint32_t r = 0;
if(x & 0xffff0000){
r += 16;
x >>= 16;
}
if(x & 0xff00){
r += 8;
x >>= 8;
}
if(x & 0xf0){
r += 4;
x >>= 4;
}
if(x & 0x0c){
r += 2;
x >>= 2;
}
if(x & 0x02){
r += 1;
}
return r;
}
/// GetHighestBitPowerOf2 (a.k.a. GetHighestBitIndex)
/// How to detect the power of 2 of the highest bit set in a uint64_t.
/// The power of 2 is the same as the bit index, so this could also be
/// called GetHighestBitIndex.
/// Returns a value in the range of [0, 63]
/// Returns 0 for an input of 0.
/// Example:
/// GetHighestBitPowerOf2(0) -> 0
/// GetHighestBitPowerOf2(1) -> 0
/// GetHighestBitPowerOf2(2) -> 1
/// GetHighestBitPowerOf2(3) -> 1
/// GetHighestBitPowerOf2(4) -> 2
/// GetHighestBitPowerOf2(7) -> 2
/// GetHighestBitPowerOf2(8) -> 3
inline uint32_t GetHighestBitPowerOf2(uint64_t x){
uint32_t r = 0;
if(x & UINT64_C(0xffffffff00000000)){
r += 32;
x >>= 32;
}
return GetHighestBitPowerOf2((uint32_t)x) + r;
}
/// GetNextGreaterEven
/// Returns the next higher even integer.
/// Returns an even number, not necessarily a power of 2.
/// Example:
/// GetNextGreaterEven<int>(-3) -> -2
/// GetNextGreaterEven<int>(-2) -> 0
/// GetNextGreaterEven<int>(-1) -> 0
/// GetNextGreaterEven<int>( 0) -> 2
/// GetNextGreaterEven<int>( 1) -> 2
/// GetNextGreaterEven<int>( 2) -> 4
/// GetNextGreaterEven<int>( 3) -> 4
template <typename T>
inline T GetNextGreaterEven(T x)
{
return (x + 2) & -2;
}
/// GetNextGreaterOdd
/// Returns the next higher odd integer.
/// Returns an even number, not necessarily a power of 2.
/// Example:
/// GetNextGreaterOdd<int>(-3) -> -1
/// GetNextGreaterOdd<int>(-2) -> -1
/// GetNextGreaterOdd<int>(-1) -> 1
/// GetNextGreaterOdd<int>( 0) -> 1
/// GetNextGreaterOdd<int>( 1) -> 3
/// GetNextGreaterOdd<int>( 2) -> 3
/// GetNextGreaterOdd<int>( 3) -> 5
template <typename T>
inline T GetNextGreaterOdd(T x)
{
return ((x + 1) & -2) + 1;
}
/// RoundUpTo
/// Template constant n is required to be a power of 2.
/// Rounds values towards positive infinity.
/// Returns 0 for an input of 0.
/// Example:
/// RoundUpTo<int, 4>(3) -> 4
/// RoundUpTo<int, 4>(8) -> 8
/// RoundUpTo<int, 4>(0) -> 0
/// RoundUpTo<int, 4>(-7) -> -4
template <typename T, int n>
inline T RoundUpTo(T x){
return (T)((x + (n - 1)) & (T)-n);
}
/// RoundUpToEx
/// Template constant n is required to be a power of 2.
/// Rounds values away from zero.
/// Returns 0 for an input of 0.
/// Example:
/// RoundUpToEx<int, 4>(3) -> 4
///
template <bool is_signed>
struct RoundUpToExStruct
{
template <typename T, int n>
static T RoundUpToEx(T x){
if(x >= 0)
return (T)((x + (n - 1)) & (T)-n);
return (T)-(bt_signed)((-(bt_signed)x + (n - 1)) & (T)-n);
}
};
template <>
struct RoundUpToExStruct<false>
{
template <typename T, int n>
static T RoundUpToEx(T x){
return (T)((x + (n - 1)) & (T)-n);
}
};
template <typename T, int n>
inline T RoundUpToEx(T x){
return RoundUpToExStruct<bt_is_signed>::template RoundUpToEx<T, n>(x);
}
/// RoundDownTo
/// Template constant n is required to be a power of 2.
/// Returns 0 for an input of 0.
/// Rounds values towards negative infinity.
/// Example:
/// RoundDownTo<int, 4>(5) -> 4
/// RoundDownTo<int, 4>(4) -> 4
/// RoundDownTo<int, 4>(0) -> 0
/// RoundDownTo<int, 4>(-7) -> -8
template <typename T, int n>
inline T RoundDownTo(T x){
return (T)(x & ~(n - 1));
}
/// RoundDownToEx
/// Template constant n is required to be a power of 2.
/// Returns 0 for an input of 0.
/// Rounds values towards zero.
/// Example:
/// RoundDownTo<int, 4>(5) -> 4
/// RoundDownTo<int, 4>(4) -> 4
/// RoundDownTo<int, 4>(0) -> 0
/// RoundDownTo<int, 4>(-7) -> -4
///
template <bool is_signed>
struct RoundDownToExStruct
{
template <typename T, int n>
static T RoundDownToEx(T x){
if(x >= 0)
return (T)(x & ~(n - 1));
return (T)-(bt_signed)(-(bt_signed)x & ~(n - 1));
}
};
template <>
struct RoundDownToExStruct<false>
{
template <typename T, int n>
static T RoundDownToEx(T x){
return (T)(x & ~(n - 1));
}
};
template <typename T, int n>
inline T RoundDownToEx(T x){
return RoundDownToExStruct<bt_is_signed>::template RoundDownToEx<T, n>(x);
}
/// RoundUpToMultiple
/// This is a non-power of 2 function; n may be any value > zero.
/// Rounds values towards infinity.
/// Example:
/// RoundUpToMultiple<int, 6>(37) -> 42
/// RoundUpToMultiple<int, 6>(42) -> 42
template <typename T, int n>
inline T RoundUpToMultiple(T x){
return (T)(((x + (n - 1)) / n) * n);