-
Notifications
You must be signed in to change notification settings - Fork 4
/
bithacks.zig
1708 lines (1491 loc) · 68.2 KB
/
bithacks.zig
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
// Zig Bit Twiddling Hacks
// https://github.com/cryptocode/bithacks
//
// Like the original snippets, this file is released under public domain:
//
// The code and descriptions are distributed in the hope that they will
// be useful, but WITHOUT ANY WARRANTY and without even the implied
// warranty of merchantability or fitness for a particular purpose.
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const assert = std.debug.assert;
/// Asserts at compile time that `T` is an integer, returns `T`
pub fn requireInt(comptime T: type) type {
comptime assert(@typeInfo(T) == .int);
return T;
}
/// Asserts at compile time that `T` is a nsigned integer, returns `T`
pub fn requireSignedInt(comptime T: type) type {
_ = requireInt(T);
comptime assert(@typeInfo(T).int.signedness == .signed);
return T;
}
/// Asserts at compile time that `T` is an unsigned integer, returns `T`
pub fn requireUnsignedInt(comptime T: type) type {
_ = requireInt(T);
comptime assert(@typeInfo(T).int.signedness == .unsigned);
return T;
}
/// Compute the sign of an integer
/// Returns true if the sign bit of `val` is set, otherwise false
/// https://github.com/cryptocode/bithacks#CopyIntegerSign
pub fn isSignBitSet(val: anytype) bool {
const T = requireSignedInt(@TypeOf(val));
return -(@as(T, @intCast(@intFromBool(val < 0)))) == -1;
}
test "Compute the sign of an integer" {
const cases = [5]i32{ std.math.minInt(i32), -1, 0, 1, std.math.maxInt(i32) };
const expected = [5]bool{ true, true, false, false, false };
for (cases, 0..) |num, i| {
try expect(isSignBitSet(num) == expected[i]);
}
}
/// Detect if two integers have opposite signs
/// Returns true if the `first` and `second` signed integers have opposite signs
/// https://github.com/cryptocode/bithacks#detect-if-two-integers-have-opposite-signs
pub fn isOppositeSign(first: anytype, second: @TypeOf(first)) bool {
_ = requireSignedInt(@TypeOf(first));
return (first ^ second) < 0;
}
test "Detect if two integers have opposite signs" {
try expect(isOppositeSign(@as(i32, -1), @as(i32, 1)));
try expect(!isOppositeSign(@as(i32, 1), @as(i32, 1)));
}
/// Compute the integer absolute value (abs) without branching
/// https://github.com/cryptocode/bithacks#compute-the-integer-absolute-value-abs-without-branching
pub fn absFast(val: anytype) @TypeOf(val) {
const T = requireSignedInt(@TypeOf(val));
const bits = @typeInfo(T).int.bits;
const mask: T = val >> (bits - 1);
return (val + mask) ^ mask;
}
test "Compute the integer absolute value (abs) without branching" {
const cases = [5]i32{ std.math.minInt(i32) + 1, -1, 0, 1, std.math.maxInt(i32) };
const expected = [5]i32{ std.math.maxInt(i32), 1, 0, 1, std.math.maxInt(i32) };
for (cases, 0..) |num, i| {
try expect(absFast(num) == expected[i]);
}
}
/// Find the minimum of two integers without branching
/// https://github.com/cryptocode/bithacks#compute-the-minimum-min-or-maximum-max-of-two-integers-without-branching
pub fn minFast(x: anytype, y: @TypeOf(x)) @TypeOf(x) {
_ = requireSignedInt(@TypeOf(x));
return y ^ ((x ^ y) & -@as(@TypeOf(x), @intCast(@intFromBool((x < y)))));
}
/// Find the maximum of two signed integers without branching
/// https://github.com/cryptocode/bithacks#compute-the-minimum-min-or-maximum-max-of-two-integers-without-branching
pub fn maxFast(x: anytype, y: @TypeOf(x)) @TypeOf(x) {
_ = requireSignedInt(@TypeOf(x));
return x ^ ((x ^ y) & -@as(@TypeOf(x), @intCast(@intFromBool((x < y)))));
}
test "Compute the minimum (min) or maximum (max) of two integers without branching" {
const x: i32 = 19;
const y: i32 = -13;
try expect(minFast(x, y) == y);
try expect(maxFast(x, y) == x);
}
/// Determining if an integer is a power of 2
/// Generic function that checks if the input integer is a power of 2. If the input
/// is a signed integer, the generated function will include a call to absFast()
/// https://github.com/cryptocode/bithacks#determining-if-an-integer-is-a-power-of-2
pub fn isPowerOf2(val: anytype) bool {
const T = @TypeOf(val);
const abs = if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed) absFast(val) else val;
return abs != 0 and (abs & (abs - 1)) == 0;
}
test "Determining if an integer is a power of 2" {
try expect(isPowerOf2(@as(i32, -64)));
try expect(!isPowerOf2(@as(i32, -63)));
try expect(isPowerOf2(@as(u32, 64)));
try expect(!isPowerOf2(@as(u32, 63)));
try expect(!isPowerOf2(@as(u32, 0)));
}
/// Sign extending from a constant bit-width
/// Input `val` is an unsigned n-bit numbers that is reinterpreted as a signed integer which
/// is then signed-extended to the `target` type and returned.
/// https://github.com/cryptocode/bithacks#sign-extending-from-a-constant-bit-width
pub fn signExtendFixed(comptime target: type, val: anytype) target {
const T = requireUnsignedInt(@TypeOf(val));
const SignedType = std.meta.Int(.signed, @typeInfo(T).int.bits);
return @as(SignedType, @bitCast(val));
}
test "Sign extending from a constant bit-width2" {
// Input is -3 in 4-bit two's complement representation, which we sign extend to an i16
try expectEqual(signExtendFixed(i16, @as(u4, 0b1101)), -3);
try expectEqual(signExtendFixed(i16, @as(u5, 0b10000)), -16);
}
/// Sign extending from a variable bit-width
/// The `val` argument is an integer with size >= `bits`, but only `bits` number of bits actually
/// represents the number to be sign-extended to the `target` type.
/// https://github.com/cryptocode/bithacks#sign-extending-from-a-variable-bit-width
pub fn signExtendVariable(comptime target: type, comptime bits: usize, val: anytype) target {
return @as(target, @as(std.meta.Int(.signed, bits), @truncate(val)));
}
test "Sign extending from a variable bit-width" {
// Input is 0b10110110, but we only care about the lower 3 bits which we sign extend into an i16
const res = signExtendVariable(i16, 3, @as(i8, @bitCast(@as(u8, 0b10110110))));
try expectEqual(res, -2);
}
/// Conditionally set or clear bits without branching
/// https://github.com/cryptocode/bithacks#conditionally-set-or-clear-bits-without-branching
pub fn setOrClearBits(set: bool, mask: anytype, val: anytype) @TypeOf(val) {
_ = requireInt(@TypeOf(mask));
const T = requireInt(@TypeOf(val));
return (val & ~mask) | (-%@as(T, @intFromBool(set)) & mask);
}
test "Conditionally set or clear bits without branching" {
const mask: u8 = 0b10110010;
const bits: u8 = 0b01000011;
var res = setOrClearBits(true, mask, bits);
try expect(res == 0b11110011);
res = setOrClearBits(false, mask, bits);
try expectEqual(res, 0b01000001);
}
/// Conditionally negate a value without branching
/// https://github.com/cryptocode/bithacks#conditionally-negate-a-value-without-branching
pub fn negateIf(negate: bool, val: anytype) @TypeOf(val) {
const T = requireSignedInt(@TypeOf(val));
const negate_as_int = @as(T, @intFromBool(negate));
return (val ^ -negate_as_int) + negate_as_int;
}
test "Conditionally negate a value without branching" {
try expectEqual(negateIf(true, @as(i32, 50)), -50);
try expectEqual(negateIf(false, @as(i32, 50)), 50);
}
/// Merge bits from two values according to a mask"
/// https://github.com/cryptocode/bithacks#merge-bits-from-two-values-according-to-a-mask
pub fn mergeBits(first: anytype, second: @TypeOf(first), mask: @TypeOf(first)) @TypeOf(first) {
_ = requireUnsignedInt(@TypeOf(first));
return first ^ ((first ^ second) & mask);
}
test "Merge bits from two values according to a mask" {
const a: u8 = 0b10110010;
const b: u8 = 0b00001101;
// 1 = which bits to pick from a
// 0 = which bits to pick from b
const m: u8 = 0b00001111;
try expectEqual(mergeBits(a, b, m), 0b10111101);
}
/// Counting bits set (naive way)
/// https://github.com/cryptocode/bithacks#counting-bits-set-naive-way
pub fn countBitsSetNaive(val: anytype) usize {
const T = requireInt(@TypeOf(val));
var v = val;
var bits_set: T = 0;
while (v != 0) : (v >>= 1) {
bits_set +%= v & 1;
}
return @as(usize, @intCast(bits_set));
}
test "Counting bits set (naive way)" {
try expectEqual(countBitsSetNaive(@as(u8, 0b0)), 0);
try expectEqual(countBitsSetNaive(@as(u8, 0b11100011)), 5);
try expectEqual(countBitsSetNaive(@as(u8, 0b11111111)), 8);
try expectEqual(countBitsSetNaive(@as(i8, 0b1111111)), 7);
try expectEqual(countBitsSetNaive(@as(u32, 0xffffffff)), 32);
try expectEqual(countBitsSetNaive(@as(u64, 0xffffffffffffffff)), 64);
}
/// Counting bits set by lookup table
/// https://github.com/cryptocode/bithacks#counting-bits-set-by-lookup-table
pub fn countBitsByLookupTable(val: u32) usize {
// Generate the lookup table at compile time
const bitSetTable = comptime val: {
var table: [256]u8 = undefined;
table[0] = 0;
var i: usize = 0;
while (i < 256) : (i += 1) {
table[i] = (i & 1) + table[i / 2];
}
break :val table;
};
return bitSetTable[val & 0xff] +
bitSetTable[(val >> 8) & 0xff] +
bitSetTable[(val >> 16) & 0xff] +
bitSetTable[val >> 24];
}
test "Counting bits set by lookup table" {
try expectEqual(countBitsByLookupTable(0b0), 0);
try expectEqual(countBitsByLookupTable(0b11100011), 5);
try expectEqual(countBitsByLookupTable(0b1111111), 7);
try expectEqual(countBitsByLookupTable(0b11111111), 8);
try expectEqual(countBitsByLookupTable(0xffffffff), 32);
}
/// Counting bits set, Brian Kernighan's way
/// https://github.com/cryptocode/bithacks#counting-bits-set-brian-kernighans-way
pub fn countBitsSetKernighan(val: anytype) usize {
_ = requireInt(@TypeOf(val));
var v = val;
var bits_set: usize = 0;
while (v != 0) : (bits_set += 1) {
v &= v - 1;
}
return @as(usize, @truncate(bits_set));
}
test "Counting bits set, Brian Kernighan's way" {
try expectEqual(countBitsSetKernighan(@as(u8, 0b0)), 0);
try expectEqual(countBitsSetKernighan(@as(u8, 0b11100011)), 5);
try expectEqual(countBitsSetKernighan(@as(u8, 0b11111111)), 8);
try expectEqual(countBitsSetKernighan(@as(i8, 0b1111111)), 7);
try expectEqual(countBitsSetKernighan(@as(u32, 0xffffffff)), 32);
try expectEqual(countBitsSetKernighan(@as(u64, 0xffffffffffffffff)), 64);
}
/// Counting bits set in 14, 24, or 32-bit words using 64-bit instructions
/// https://github.com/cryptocode/bithacks#counting-bits-set-in-14-24-or-32-bit-words-using-64-bit-instructions
pub fn countBitsSetModulus(val: anytype) usize {
const T = requireInt(@TypeOf(val));
const bits_set: u64 = switch (@typeInfo(T).int.bits) {
14 => (val * @as(u64, 0x200040008001) & @as(u64, 0x111111111111111)) % 0xf,
24 => res: {
var c: u64 = ((@as(u64, @intCast(val)) & 0xfff) * @as(u64, 0x1001001001001) & @as(u64, 0x84210842108421)) % 0x1f;
c += (((@as(u64, @intCast(val)) & 0xfff000) >> 12) * @as(u64, 0x1001001001001) & @as(u64, 0x84210842108421)) % 0x1f;
break :res c;
},
32 => res: {
var c: u64 = ((val & 0xfff) * @as(u64, 0x1001001001001) & @as(u64, 0x84210842108421)) % 0x1f;
c += (((val & 0xfff000) >> 12) * @as(u64, 0x1001001001001) & @as(u64, 0x84210842108421)) % 0x1f;
c += ((val >> 24) * @as(u64, 0x1001001001001) & @as(u64, 0x84210842108421)) % 0x1f;
break :res c;
},
else => @panic("Invalid integer size"),
};
return @as(usize, @truncate(bits_set));
}
test "Counting bits set in 14, 24, or 32-bit words using 64-bit instructions" {
try expectEqual(countBitsSetModulus(@as(u14, 0b11111111111110)), 13);
try expectEqual(countBitsSetModulus(@as(u14, 0b11111111111111)), 14);
try expectEqual(countBitsSetModulus(@as(u24, 0b111111111111111111111110)), 23);
try expectEqual(countBitsSetModulus(@as(u24, 0b111111111111111111111111)), 24);
try expectEqual(countBitsSetModulus(@as(u32, 0b0)), 0);
try expectEqual(countBitsSetModulus(@as(u32, 0b11100011)), 5);
try expectEqual(countBitsSetModulus(@as(u32, 0b11111111)), 8);
try expectEqual(countBitsSetModulus(@as(u32, 0xfffffffe)), 31);
try expectEqual(countBitsSetModulus(@as(u32, 0xffffffff)), 32);
}
/// Counting bits set, in parallel
/// https://github.com/cryptocode/bithacks#counting-bits-set-in-parallel
pub fn countBitsSetParallel(val: anytype) @TypeOf(val) {
const T = requireUnsignedInt(@TypeOf(val));
var v = val;
var bits_set: T = 0;
const ones = ~@as(T, 0);
switch (@typeInfo(T).int.bits) {
// Method optimized for 32 bit integers
32 => {
v = v - ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
bits_set = ((v + (v >> 4) & 0xF0F0F0F) *% 0x1010101) >> 24;
},
// Generalized version for integers up to 128 bits in width
else => |bits| {
v = v - ((v >> 1) & @as(T, ones / 3));
v = (v & @as(T, ones / 15 * 3)) + ((v >> 2) & @as(T, ones / 15 * 3));
v = (v + (v >> 4)) & @as(T, ones / 255 * 15);
bits_set = @as(T, (v *% (@as(T, ones / 255))) >> (bits / 8 - 1) * 8);
},
}
return bits_set;
}
test "Counting bits set, in parallel" {
try expectEqual(countBitsSetParallel(@as(u16, 0xfffe)), 15);
try expectEqual(countBitsSetParallel(@as(u16, 0xffff)), 16);
try expectEqual(countBitsSetParallel(@as(u32, 0b0)), 0);
try expectEqual(countBitsSetParallel(@as(u32, 0b11100011)), 5);
try expectEqual(countBitsSetParallel(@as(u32, 0b11111111)), 8);
try expectEqual(countBitsSetParallel(@as(u32, 0xfffffffe)), 31);
try expectEqual(countBitsSetParallel(@as(u32, 0xffffffff)), 32);
try expectEqual(countBitsSetParallel(@as(u64, 0x0)), 0);
try expectEqual(countBitsSetParallel(@as(u64, 0x1)), 1);
try expectEqual(countBitsSetParallel(@as(u64, 0xfffffffffffffffe)), 63);
try expectEqual(countBitsSetParallel(@as(u64, 0xffffffffffffffff)), 64);
try expectEqual(countBitsSetParallel(@as(u128, 0x0)), 0);
try expectEqual(countBitsSetParallel(@as(u128, 0x1)), 1);
try expectEqual(countBitsSetParallel(@as(u128, 0xfffffffffffffffffffffffffffffffe)), 127);
try expectEqual(countBitsSetParallel(@as(u128, 0xffffffffffffffffffffffffffffffff)), 128);
}
/// Count bits set (rank) from the most-significant bit upto a given position
/// Returns rank of MSB bits in `val` downto LSB `pos`
/// https://github.com/cryptocode/bithacks#count-bits-set-rank-from-the-most-significant-bit-upto-a-given-position
pub fn countBitsRank(val: u64, pos: u64) u64 {
const ones = ~@as(u64, 0);
const bits = @as(u64, 64);
// The following finds the the rank of a bit, meaning it returns the sum of bits that
// are set to 1 from the most-signficant bit downto the bit at the given position.
var r: u64 = val >> @as(u6, @intCast((bits -% pos)));
r = r - ((r >> 1) & ones / 3);
r = (r & ones / 5) + ((r >> 2) & ones / 5);
r = (r +% (r >> 4)) & ones / 17;
r = (r *% (ones / 255)) >> ((8 - 1) *% 8);
return r;
}
test "Count bits set (rank) from the most-significant bit upto a given position" {
try expectEqual((countBitsRank(0x0, 64)), 0);
try expectEqual((countBitsRank(0x1, 64)), 1);
try expectEqual((countBitsRank(0x1, 1)), 0);
try expectEqual((countBitsRank(0xefffffffffffffff, 7)), 6);
try expectEqual((countBitsRank(0xffffffffffffffff, 64)), 64);
}
/// Select the bit position (from the most-significant bit) with the given count `rank`
/// https://github.com/cryptocode/bithacks#SelectPosFromMSBRank
pub fn bitPosOfRank(val: u64, rank: u64) u64 {
const ones = ~@as(u64, 0);
// Do a normal parallel bit count for a 64-bit integer, but store all intermediate steps:
const a: u64 = val - ((val >> 1) & ones / 3);
const b: u64 = (a & ones / 5) + ((a >> 2) & ones / 5);
const c: u64 = (b +% (b >> 4)) & ones / 0x11;
const d: u64 = (c +% (c >> 8)) & ones / 0x101;
var t: u64 = (d >> 32) + (d >> 48);
var r = rank;
// Now do branchless select:
var s: u64 = 64;
s -%= (t -% r) & 256 >> @as(u6, 3);
r -%= (t & ((t -% r) >> 8));
t = (d >> @as(u6, @intCast((s -% @as(u64, 16))))) & 0xff;
s -%= ((t -% r) & 256) >> 4;
r -%= (t & ((t -% r) >> 8));
t = (c >> @as(u6, @intCast((s -% 8)))) & 0xf;
s -%= ((t -% r) & 256) >> 5;
r -%= (t & ((t -% r) >> 8));
t = (b >> @as(u6, @intCast((s -% 4)))) & 0x7;
s -%= ((t -% r) & 256) >> 6;
r -%= (t & ((t -% r) >> 8));
t = (a >> @as(u6, @intCast((s -% 2)))) & 0x3;
s -%= ((t -% r) & 256) >> 7;
r -%= (t & ((t -% r) >> 8));
t = (val >> @as(u6, @intCast((s -% 1)))) & 0x1;
s -%= ((t -% r) & 256) >> 8;
s = 65 -% s;
return s;
}
test "Select the bit position (from the most-significant bit) with the given count (rank)" {
try expectEqual((bitPosOfRank(0xffffffffffffffff, 64)), 64);
try expectEqual((bitPosOfRank(0x00ffffffffffffff, 1)), 9);
}
/// Computing parity the naive way
/// Returns true when an odd number of bits are set in `val`
/// https://github.com/cryptocode/bithacks#computing-parity-the-naive-way
pub fn parityNaive(val: anytype) bool {
_ = requireInt(@TypeOf(val));
var parity = false;
var v = val;
while (v != 0) {
parity = !parity;
v = v & (v - 1);
}
return parity;
}
test "Computing parity the naive way" {
try expect(!parityNaive(@as(u8, 0x0)));
try expect(!parityNaive(@as(u8, 0xf)));
try expect(!parityNaive(@as(u8, 0xff)));
try expect(parityNaive(@as(u8, 0x1)));
try expect(parityNaive(@as(u8, 0x7)));
try expect(parityNaive(@as(u32, 2)));
try expect(parityNaive(@as(u32, 4)));
try expect(parityNaive(@as(u32, 7)));
try expect(!parityNaive(@as(u32, 0)));
try expect(!parityNaive(@as(u32, 3)));
}
/// Compute parity by lookup table
/// Returns true when an odd number of bits are set in `val` which must be an 8-bit or 32-bit unsigned integer.
/// https://github.com/cryptocode/bithacks#compute-parity-by-lookup-table
pub fn parityByLookupTable(val: anytype) bool {
const T = requireUnsignedInt(@TypeOf(val));
comptime assert(@typeInfo(T).int.bits == 8 or @typeInfo(T).int.bits == 32);
// Generate the lookup table at compile time which determines if the n'th number has an odd number of bits.
// The table can be viewed as a 16 by 16 bit-matrix generated from a seed following these rules:
// For each row n in [0..15], if the n'th bit in the seed is 0, use the seed as the row,
// otherwise use the inverted seed as the row.
const seed: u16 = 0b0110100110010110;
const parityTable = comptime val: {
var table: [16]u16 = undefined;
var row: usize = 0;
while (row < 16) : (row += 1) {
table[row] = if (seed & (1 << (15 - row)) == 0) seed else ~seed;
}
break :val table;
};
var word = val / 16;
var bit = val % 16;
return 0 != switch (@typeInfo(T).int.bits) {
8 => parityTable[word] & (@as(u16, 0x8000) >> @as(u4, @intCast(bit))),
32 => res: {
var v = val;
v ^= v >> 16;
v ^= v >> 8;
const index = v & 0xff;
word = index / 16;
bit = index % 16;
break :res parityTable[word] & (@as(u16, 0x8000) >> @as(u4, @intCast(bit)));
},
else => @panic("Invalid integer size"),
};
}
test "Compute parity by lookup table" {
try expect(parityByLookupTable(@as(u8, 0x1)));
try expect(parityByLookupTable(@as(u8, 0x7)));
try expect(!parityByLookupTable(@as(u8, 0x0)));
try expect(!parityByLookupTable(@as(u8, 0xf)));
try expect(!parityByLookupTable(@as(u8, 0xff)));
try expect(parityByLookupTable(@as(u32, 2)));
try expect(parityByLookupTable(@as(u32, 4)));
try expect(parityByLookupTable(@as(u32, 7)));
try expect(!parityByLookupTable(@as(u32, 0)));
try expect(!parityByLookupTable(@as(u32, 3)));
}
/// Compute parity of a byte using 64-bit multiply and modulus division
/// https://github.com/cryptocode/bithacks#compute-parity-of-a-byte-using-64-bit-multiply-and-modulus-division
pub fn parityMulMod(val: u8) bool {
return 0 != (((val * @as(u64, 0x0101010101010101)) & @as(u64, 0x8040201008040201)) % 0x1FF) & 1;
}
test "Compute parity of a byte using 64-bit multiply and modulus division" {
try expect(!parityMulMod(0x0));
try expect(!parityMulMod(0xf));
try expect(!parityMulMod(0xff));
try expect(parityMulMod(0x1));
try expect(parityMulMod(0x7));
}
/// Compute parity of word with a multiply
/// The input `val` must be a 32 or 64 bit unsigned integer
/// https://github.com/cryptocode/bithacks#compute-parity-of-word-with-a-multiply
pub fn parityMul(val: anytype) bool {
const T = requireUnsignedInt(@TypeOf(val));
comptime assert(@typeInfo(T).int.bits == 32 or @typeInfo(T).int.bits == 64);
return 0 != switch (@typeInfo(T).int.bits) {
32 => res: {
var v = val;
v ^= v >> 1;
v ^= v >> 2;
v = (v & 0x11111111) *% 0x11111111;
break :res (v >> 28) & 1;
},
64 => res: {
var v = val;
v ^= v >> 1;
v ^= v >> 2;
v = (v & 0x1111111111111111) *% 0x1111111111111111;
break :res (v >> 60) & 1;
},
else => @panic("Invalid integer size"),
};
}
test "Compute parity of word with a multiply" {
try expect(parityMul(@as(u32, 2)));
try expect(parityMul(@as(u32, 4)));
try expect(parityMul(@as(u32, 7)));
try expect(!parityMul(@as(u32, 0)));
try expect(!parityMul(@as(u32, 3)));
try expect(!parityMul(@as(u32, 0xffffffff)));
try expect(parityMul(@as(u64, 2)));
try expect(parityMul(@as(u64, 4)));
try expect(parityMul(@as(u64, 7)));
try expect(!parityMul(@as(u64, 0)));
try expect(!parityMul(@as(u64, 3)));
try expect(!parityMul(@as(u64, 0xffffffffffffffff)));
}
/// Compute parity in parallel
/// Works for 32-bit unsigned integers
pub fn parityParallel(val: u32) bool {
var v = val;
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
v &= 0xf;
return 0 != ((@as(u16, 0x6996) >> @as(u4, @intCast(v))) & 1);
}
test "Compute parity in parallel" {
try expect(parityParallel(2));
try expect(parityParallel(4));
try expect(parityParallel(7));
try expect(!parityParallel(0));
try expect(!parityParallel(3));
try expect(!parityParallel(0xffffffff));
}
/// Swapping values with subtraction and addition
/// https://github.com/cryptocode/bithacks#swapping-values-with-subtraction-and-addition
pub fn swapSubAdd(a: anytype, b: anytype) void {
if (a != b) {
a.* -%= b.*;
b.* +%= a.*;
a.* = b.* -% a.*;
}
}
test "Swapping values with subtraction and addition" {
var a: u32 = 0x1dfa8ce1;
var b: u32 = 0xffeeddcc;
swapSubAdd(&a, &b);
try expectEqual(a, 0xffeeddcc);
try expectEqual(b, 0x1dfa8ce1);
}
/// Swapping values with XOR
/// https://github.com/cryptocode/bithacks#swapping-values-with-xor
pub fn swapXor(a: anytype, b: anytype) void {
if (a != b) {
a.* ^= b.*;
b.* ^= a.*;
a.* ^= b.*;
}
}
test "Swapping values with XOR" {
var a: u32 = 0x1dfa8ce1;
var b: u32 = 0xffeeddcc;
swapXor(&a, &b);
try expectEqual(a, 0xffeeddcc);
try expectEqual(b, 0x1dfa8ce1);
}
/// Swapping individual bits with XOR
/// https://github.com/cryptocode/bithacks#swapping-individual-bits-with-xor
pub fn swapBitsXor(pos1: usize, pos2: usize, consecutiveBits: usize, val: anytype) @TypeOf(val) {
const T = requireInt(@TypeOf(val));
const shiftType = std.math.Log2Int(T);
const x: T = ((val >> @as(shiftType, @intCast(pos1))) ^ (val >> @as(shiftType, @intCast(pos2)))) & ((@as(T, 1) << @as(shiftType, @intCast(consecutiveBits))) - 1);
return val ^ ((x << @as(shiftType, @intCast(pos1))) | (x << @as(shiftType, @intCast(pos2))));
}
test "Swapping individual bits with XOR" {
try expectEqual(swapBitsXor(0, 4, 4, @as(u8, 0b11110000)), 0b00001111);
try expectEqual(swapBitsXor(0, 16, 16, @as(u32, 0xffff0000)), 0x0000ffff);
}
/// Reverse bits the obvious way
/// https://github.com/cryptocode/bithacks#reverse-bits-the-obvious-way
pub fn reverseObvious(val: anytype) @TypeOf(val) {
const T = requireInt(@TypeOf(val));
const bits = @typeInfo(T).int.bits;
const shiftType = std.math.Log2Int(T);
var finalShiftsNeeded: shiftType = bits - 1;
var v = val >> 1;
var res = val;
while (v != 0) {
res <<= 1;
res |= v & 1;
finalShiftsNeeded -%= 1;
v >>= 1;
}
return (res << finalShiftsNeeded);
}
test "Reverse bits the obvious way" {
try expectEqual(reverseObvious(@as(u8, 0b11010010)), 0b01001011);
try expectEqual(reverseObvious(@as(u8, 0b00000001)), 0b10000000);
try expectEqual(reverseObvious(@as(u32, 0xfffffffe)), 0x7fffffff);
try expectEqual(reverseObvious(@as(u32, 0xffffffff)), 0xffffffff);
try expectEqual(reverseObvious(@as(u32, 0)), 0);
try expectEqual(reverseObvious(@as(u32, 1)), 0x80000000);
try expectEqual(reverseObvious(@as(u64, 0xfffffffffffffffe)), 0x7fffffffffffffff);
}
/// Reverse bits in word by lookup table
/// This is specific to 32-bit unsigned integers
/// https://github.com/cryptocode/bithacks#reverse-bits-in-word-by-lookup-table
pub fn reverseByLookup(val: u32) u32 {
// Generate the lookup table at compile time. This corresponds to the macro-compacted C version.
const reverseTable = comptime val: {
var tblgen = struct {
i: usize = 0,
t: [256]u8 = undefined,
pub fn R2(self: *@This(), n: u8) void {
self.t[self.i + 0] = n;
self.t[self.i + 1] = n + 2 * 64;
self.t[self.i + 2] = n + 1 * 64;
self.t[self.i + 3] = n + 3 * 64;
self.i += 4;
}
pub fn R4(self: *@This(), n: u8) void {
self.R2(n);
self.R2(n + 2 * 16);
self.R2(n + 1 * 16);
self.R2(n + 3 * 16);
}
pub fn R6(self: *@This(), n: u8) void {
self.R4(n);
self.R4(n + 2 * 4);
self.R4(n + 1 * 4);
self.R4(n + 3 * 4);
}
}{};
tblgen.R6(0);
tblgen.R6(2);
tblgen.R6(1);
tblgen.R6(3);
break :val tblgen.t;
};
return (@as(u32, @intCast(reverseTable[val & 0xff])) << 24) |
(@as(u32, @intCast(reverseTable[(val >> 8) & 0xff])) << 16) |
(@as(u32, @intCast(reverseTable[(val >> 16) & 0xff])) << 8) |
(@as(u32, @intCast(reverseTable[(val >> 24) & 0xff])));
}
test "Reverse bits in word by lookup table" {
try expectEqual(reverseByLookup(0xfffffffe), 0x7fffffff);
try expectEqual(reverseByLookup(0xffffffff), 0xffffffff);
try expectEqual(reverseByLookup(0), 0);
try expectEqual(reverseByLookup(1), 0x80000000);
}
/// Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)
/// https://github.com/cryptocode/bithacks#reverse-the-bits-in-a-byte-with-3-operations-64-bit-multiply-and-modulus-division
pub fn reverseByteMulMod(val: u8) u8 {
return @as(u8, @truncate((val * @as(u64, 0x0202020202) & @as(u64, 0x010884422010)) % 1023));
}
test "Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)" {
try expectEqual(reverseByteMulMod(0b11010010), 0b01001011);
try expectEqual(reverseByteMulMod(0b00000001), 0b10000000);
try expectEqual(reverseByteMulMod(0), 0);
}
/// Reverse the bits in a byte with 4 operations (64-bit multiply, no division)
/// https://github.com/cryptocode/bithacks#reverse-the-bits-in-a-byte-with-4-operations-64-bit-multiply-no-division
pub fn reverseByteMulNoDiv(val: u8) u8 {
return @as(u8, @truncate(((val * @as(u64, 0x80200802)) & @as(u64, 0x0884422110)) *% @as(u64, 0x0101010101) >> 32));
}
test "Reverse the bits in a byte with 4 operations (64-bit multiply, no division)" {
try expectEqual(reverseByteMulNoDiv(0b11010010), 0b01001011);
try expectEqual(reverseByteMulNoDiv(0b00000001), 0b10000000);
try expectEqual(reverseByteMulNoDiv(0), 0);
}
/// Reverse the bits in a byte with 7 operations (no 64-bit)
/// https://github.com/cryptocode/bithacks#reverse-the-bits-in-a-byte-with-7-operations-no-64-bit
pub fn reverseByte7ops(val: u8) u8 {
return @as(u8, @truncate(((val *% @as(u64, 0x0802) & @as(u64, 0x22110)) |
(val *% @as(u64, 0x8020) & @as(u64, 0x88440))) *% @as(u64, 0x10101) >> 16));
}
test "Reverse the bits in a byte with 7 operations (no 64-bit)" {
try expectEqual(reverseByte7ops(0b11010010), 0b01001011);
try expectEqual(reverseByte7ops(0b00000001), 0b10000000);
try expectEqual(reverseByte7ops(0), 0);
}
/// Reverse an N-bit quantity in parallel in 5 * lg(N) operations
/// https://github.com/cryptocode/bithacks#reverse-an-n-bit-quantity-in-parallel-in-5--lgn-operations
pub fn reverseInLog5steps(val: anytype) @TypeOf(val) {
const T = requireInt(@TypeOf(val));
const bits = @typeInfo(T).int.bits;
comptime assert(std.math.isPowerOfTwo(bits));
const shiftType = std.math.Log2Int(T);
var v = val;
var s: T = bits >> 1;
var mask = ~@as(T, 0);
while (s > 0) : (s >>= 1) {
mask ^= (mask << @as(shiftType, @intCast(s)));
v = ((v >> @as(shiftType, @intCast(s))) & mask) | ((v << @as(shiftType, @intCast(s))) & ~mask);
}
return v;
}
test "Reverse an N-bit quantity in parallel in 5 * lg(N) operations" {
try expectEqual(reverseInLog5steps(@as(u32, 0xfffffffe)), 0x7fffffff);
try expectEqual(reverseInLog5steps(@as(u32, 0xffffffff)), 0xffffffff);
try expectEqual(reverseInLog5steps(@as(u32, 0)), 0);
try expectEqual(reverseInLog5steps(@as(u32, 1)), 0x80000000);
try expectEqual(reverseInLog5steps(@as(i32, 1)), -0x80000000);
try expectEqual(reverseInLog5steps(@as(u64, 0xfffffffffffffffe)), 0x7fffffffffffffff);
}
/// Compute modulus division by 1 << s without a division operator
/// Returns `numerator` % (1 << `shiftAmount`), i.e. `numerator` % 2^n
/// https://github.com/cryptocode/bithacks#compute-modulus-division-by-1--s-without-a-division-operator
pub fn modPow2(numerator: anytype, shiftAmount: usize) @TypeOf(numerator) {
const T = requireInt(@TypeOf(numerator));
const shiftType = std.math.Log2Int(T);
const d = @as(T, 1) << @as(shiftType, @intCast(shiftAmount));
return numerator & (d - 1);
}
test "Compute modulus division by 1 << s without a division operator" {
try expectEqual(modPow2(@as(u32, 19), 5), 19);
try expectEqual(modPow2(@as(u32, 258), 8), 2);
try expectEqual(modPow2(@as(i64, 19), 5), 19);
}
/// Compute modulus division by (1 << s) - 1 without a division operator
/// Returns `numerator` % ((1 << `shiftAmount`) - 1)
/// https://github.com/cryptocode/bithacks#compute-modulus-division-by-1--s---1-without-a-division-operator
pub fn modPow2Minus1(numerator: anytype, shiftAmount: usize) @TypeOf(numerator) {
const T = requireInt(@TypeOf(numerator));
const shiftType = std.math.Log2Int(T);
const d = (@as(T, 1) << @as(shiftType, @intCast(shiftAmount))) - 1;
var n = numerator;
var m: T = numerator;
while (n > d) : (n = m) {
m = 0;
while (n != 0) : (n >>= @as(shiftType, @intCast(shiftAmount))) {
m +%= n & d;
}
}
return if (m == d) 0 else m;
}
test "Compute modulus division by (1 << s) - 1 without a division operator" {
try expectEqual(modPow2Minus1(@as(u8, 9), 3), 2);
try expectEqual(modPow2Minus1(@as(u32, 9), 3), 2);
try expectEqual(modPow2Minus1(@as(u32, 19), 3), 5);
try expectEqual(modPow2Minus1(@as(u32, 21), 2), 0);
try expectEqual(modPow2Minus1(@as(u64, 19), 3), 5);
}
/// Compute modulus division by (1 << s) - 1 in parallel without a division operator
/// https://github.com/cryptocode/bithacks#compute-modulus-division-by-1--s---1-in-parallel-without-a-division-operator
pub fn modPow2Minus1NoDiv(numerator: u32, shiftAmount: usize) u32 {
// zig fmt: off
const M: [32]u32 = .{
0x00000000, 0x55555555, 0x33333333, 0xc71c71c7,
0x0f0f0f0f, 0xc1f07c1f, 0x3f03f03f, 0xf01fc07f,
0x00ff00ff, 0x07fc01ff, 0x3ff003ff, 0xffc007ff,
0xff000fff, 0xfc001fff, 0xf0003fff, 0xc0007fff,
0x0000ffff, 0x0001ffff, 0x0003ffff, 0x0007ffff,
0x000fffff, 0x001fffff, 0x003fffff, 0x007fffff,
0x00ffffff, 0x01ffffff, 0x03ffffff, 0x07ffffff,
0x0fffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff
};
const Q: [32][6]u32 = .{
.{ 0, 0, 0, 0, 0, 0}, .{16, 8, 4, 2, 1, 1}, .{16, 8, 4, 2, 2, 2},
.{15, 6, 3, 3, 3, 3}, .{16, 8, 4, 4, 4, 4}, .{15, 5, 5, 5, 5, 5},
.{12, 6, 6, 6 , 6, 6}, .{14, 7, 7, 7, 7, 7}, .{16, 8, 8, 8, 8, 8},
.{ 9, 9, 9, 9, 9, 9}, .{10, 10, 10, 10, 10, 10}, .{11, 11, 11, 11, 11, 11},
.{12, 12, 12, 12, 12, 12}, .{13, 13, 13, 13, 13, 13}, .{14, 14, 14, 14, 14, 14},
.{15, 15, 15, 15, 15, 15}, .{16, 16, 16, 16, 16, 16}, .{17, 17, 17, 17, 17, 17},
.{18, 18, 18, 18, 18, 18}, .{19, 19, 19, 19, 19, 19}, .{20, 20, 20, 20, 20, 20},
.{21, 21, 21, 21, 21, 21}, .{22, 22, 22, 22, 22, 22}, .{23, 23, 23, 23, 23, 23},
.{24, 24, 24, 24, 24, 24}, .{25, 25, 25, 25, 25, 25}, .{26, 26, 26, 26, 26, 26},
.{27, 27, 27, 27, 27, 27}, .{28, 28, 28, 28, 28, 28}, .{29, 29, 29, 29, 29, 29},
.{30, 30, 30, 30, 30, 30}, .{31, 31, 31, 31, 31, 31}
};
const R: [32][6]u32 = .{
.{0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000},
.{0x0000ffff, 0x000000ff, 0x0000000f, 0x00000003, 0x00000001, 0x00000001},
.{0x0000ffff, 0x000000ff, 0x0000000f, 0x00000003, 0x00000003, 0x00000003},
.{0x00007fff, 0x0000003f, 0x00000007, 0x00000007, 0x00000007, 0x00000007},
.{0x0000ffff, 0x000000ff, 0x0000000f, 0x0000000f, 0x0000000f, 0x0000000f},
.{0x00007fff, 0x0000001f, 0x0000001f, 0x0000001f, 0x0000001f, 0x0000001f},
.{0x00000fff, 0x0000003f, 0x0000003f, 0x0000003f, 0x0000003f, 0x0000003f},
.{0x00003fff, 0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f},
.{0x0000ffff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff},
.{0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff},
.{0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff},
.{0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff},
.{0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff},
.{0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff},
.{0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff},
.{0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff},
.{0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff},
.{0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff},
.{0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff},
.{0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff},
.{0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff},
.{0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff},
.{0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff},
.{0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff},
.{0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff},
.{0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff},
.{0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff},
.{0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff},
.{0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff},
.{0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff},
.{0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff},
.{0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff}
};
// zig fmt: on
const shiftType = std.math.Log2Int(u32);
const s = shiftAmount;
const d = (@as(u32, 1) << @as(shiftType, @intCast(shiftAmount))) - 1;
const n = numerator;
var m: u32 = (n & M[s]) +% ((n >> @as(shiftType, @intCast(s))) & M[s]);
var q: usize = 0;
var r: usize = 0;
while (m > d) : ({
q += 1;
r += 1;
}) {
m = (m >> @as(shiftType, @intCast(Q[s][q]))) +% (m & R[s][r]);
}
return if (m == d) 0 else m;
}
test "Compute modulus division by (1 << s) - 1 in parallel without a division operator" {
try expectEqual(modPow2Minus1NoDiv(9, 3), 2);
try expectEqual(modPow2Minus1NoDiv(19, 3), 5);
try expectEqual(modPow2Minus1NoDiv(21, 2), 0);
}
/// Find the log base 2 of an integer with the MSB N set in O(N) operations (the obvious way)
/// Returns ⌊log2(`val`)⌋, i.e. the position of the highest bit set.
/// https://github.com/cryptocode/bithacks#find-the-log-base-2-of-an-integer-with-the-msb-n-set-in-on-operations-the-obvious-way
pub fn log2floorObvious(val: anytype) @TypeOf(val) {
const T = requireInt(@TypeOf(val));
const shiftType = std.math.Log2Int(T);
var v: T = val;
var r: T = 0;
while (true) {
v >>= @as(shiftType, @intCast(1));
if (v == 0) break;
r +%= 1;
}
return r;
}
test "Find the log base 2 of an integer with the MSB N set in O(N) operations (the obvious way)" {
try expectEqual(log2floorObvious(@as(u8, 127)), 6);
try expectEqual(log2floorObvious(@as(u32, 0)), 0);
try expectEqual(log2floorObvious(@as(u32, 1)), 0);
try expectEqual(log2floorObvious(@as(u32, 2)), 1);
try expectEqual(log2floorObvious(@as(u32, 127)), 6);
try expectEqual(log2floorObvious(@as(u32, 128)), 7);
try expectEqual(log2floorObvious(@as(u32, 0xffffffff)), 31);
try expectEqual(log2floorObvious(@as(u64, 0xffffffffffffffff)), 63);
}
/// Find the integer log base 2 of an integer with an 64-bit IEEE float
/// Returns ⌊log2(`val`)⌋, i.e. the position of the highest bit set.
/// An improvement over the original is that 0 as input returns 0, and is thus consistent with `log2floorObvious`
/// https://github.com/cryptocode/bithacks#find-the-integer-log-base-2-of-an-integer-with-an-64-bit-ieee-float
pub fn log2usingFloat(val: u32) u32 {
const endian = @import("builtin").target.cpu.arch.endian();
const little_endian: bool = switch (endian) {
.little => true,
.big => false,
};
const U = extern union {
u: [2]u32,
d: f64,
};
if (val > 0) {
var conv: U = undefined;
conv.u[@intFromBool(little_endian)] = 0x43300000;
conv.u[@intFromBool(!little_endian)] = val;
conv.d -= 4503599627370496.0;
return (conv.u[@intFromBool(little_endian)] >> 20) -% 0x3FF;
} else {
return 0;
}
}
test "Find the integer log base 2 of an integer with an 64-bit IEEE float" {
try expectEqual(log2usingFloat(0), 0);
try expectEqual(log2usingFloat(1), 0);
try expectEqual(log2usingFloat(2), 1);
try expectEqual(log2usingFloat(127), 6);
try expectEqual(log2usingFloat(128), 7);
try expectEqual(log2usingFloat(0xffffffff), 31);
}
/// Find the log base 2 of an integer with a lookup table
/// Returns ⌊log2(`val`)⌋, i.e. the position of the highest bit set.
/// https://github.com/cryptocode/bithacks#find-the-log-base-2-of-an-integer-with-a-lookup-table
pub fn log2usingLookupTable(val: u32) u32 {
// Build log table at compile time
const logTable = comptime val: {
var table: [256]u8 = undefined;
table[0] = 0;
table[1] = 0;
var i: usize = 2;
while (i < 256) : (i += 1) {
table[i] = 1 + table[i / 2];
}
break :val table;
};
const tt: u32 = val >> 16;
var t: u32 = undefined;
if (tt != 0) {
t = tt >> 8;
return if (t != 0) 24 + logTable[t] else 16 + logTable[tt];