lazarus使用CNvcl 中的CNSM4

参考了Yang杨。老师的代码,原来是delphi代码,因为个人转到lazarus,所以进行移植了。

方法如下:下载最新的CNVCL,CnNative,要修改一下,其它引用单元注释掉

  

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
{******************************************************************************}
{                       CnPack For Delphi/C++Builder                           }
{                     中国人自己的开放源码第三方开发包                         }
{                   (C)Copyright 2001-2024 CnPack 开发组                       }
{                   ------------------------------------                       }
 
{            本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修        }
{        改和重新发布这一程序。                                                }
 
{            发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有        }
{        适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。        }
 
{            您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果        }
{        还没有,可访问我们的网站:                                            }
 
{            网站地址:http://www.cnpack.org                                   }
{            电子邮件:master@cnpack.org                                       }
 
{******************************************************************************}
 
unit CnNative;
 
{* |<PRE>
================================================================================
* 软件名称:CnPack 组件包
* 单元名称:32 位和 64 位的一些统一声明以及一堆基础实现
* 单元作者:刘啸 (liuxiao@cnpack.org)
* 备    注:Delphi XE 2 支持 32 和 64 以来,开放出的 NativeInt 和 NativeUInt 随
*           当前是 32 位还是 64 而动态变化,影响到的是 Pointer、Reference等东西。
*           考虑到兼容性,固定长度的 32 位 Cardinal/Integer 等和 Pointer 这些就
*           不能再通用了,即使 32 位下也被编译器禁止。因此本单元声明了几个类型,
*           供同时在低版本和高版本的 Delphi 中使用。
*           后来加入 UInt64 的包装,注意 D567 下不直接支持 UInt64 的运算,需要用
*           辅助函数实现,目前实现了 div 与 mod
*           另外地址运算 Integer(APtr) 在 64 位下尤其是 MacOS 上容易出现截断,需要用 NativeInt
*           后来补上大量底层的函数与工具类
* 开发平台:PWin2000 + Delphi 5.0
* 兼容测试:PWin9X/2000/XP + Delphi 5/6/7 XE 2
* 本 地 化:该单元中的字符串均符合本地化处理方式
* 修改记录:2023.08.14 V2.4
*               补上几个时间固定的函数并改名
*           2022.11.11 V2.3
*               补上几个无符号数的字节顺序调换函数
*           2022.07.23 V2.2
*               增加几个内存位运算函数与二进制转换字符串函数,并改名为 CnNative
*           2022.06.08 V2.1
*               增加四个时间固定的交换函数以及内存倒排函数
*           2022.03.14 V2.0
*               增加几个十六进制转换函数
*           2022.02.17 V1.9
*               增加 FPC 的编译支持
*           2022.02.09 V1.8
*               加入运行期的大小端判断函数
*           2021.09.05 V1.7
*               加入 Int64/UInt64 的整数次幂与根的运算函数
*           2020.10.28 V1.6
*               加入 UInt64 溢出相关的判断与运算函数
*           2020.09.06 V1.5
*               加入求 UInt64 整数平方根的函数
*           2020.07.01 V1.5
*               加入判断 32 位与 64 位有无符号数相加是否溢出的函数
*           2020.06.20 V1.4
*               加入 32 位与 64 位获取最高与最低的 1 位位置的函数
*           2020.01.01 V1.3
*               加入 32 位无符号整型的 mul 运算,在不支持 UInt64 的系统上以 Int64 代替以避免溢出
*           2018.06.05 V1.2
*               加入 64 位整型的 div/mod 运算,在不支持 UInt64 的系统上以 Int64 代替
*           2016.09.27 V1.1
*               加入 64 位整型的一些定义
*           2011.07.06 V1.0
*               创建单元,实现功能
================================================================================
|</PRE>}
 
interface
 
{.$I CnPack.inc}
 
uses
Classes, SysUtils, SysConst, Math {$IFDEF COMPILER5}, Windows {$ENDIF};
// D5 下需要引用 Windows 中的 PByte
type
{$IFDEF COMPILER5}
  PCardinal = ^Cardinal;
  {* D5 下 System 单元中未定义,定义上}
  PByte = Windows.PByte;
  {* D5 下 PByte 定义在 Windows 中,其他版本定义在 System 中,
    这里统一一下供外界使用 PByte 时无需 uses Windows,以有利于跨平台}
{$ENDIF}
{$DEFine SUPPORT_UINT64}
{$IFDEF SUPPORT_32_AND_64}
  TCnNativeInt     = NativeInt;
  TCnNativeUInt    = NativeUInt;
  TCnNativePointer = NativeInt;
  TCnNativeIntPtr  = PNativeInt;
  TCnNativeUIntPtr = PNativeUInt;
{$ELSE}
TCnNativeInt     = integer;
TCnNativeUInt    = cardinal;
TCnNativePointer = integer;
TCnNativeIntPtr  = PInteger;
TCnNativeUIntPtr = PCardinal;
{$ENDIF}
 
{$IFDEF CPU64BITS}
  TCnUInt64        = NativeUInt;
  TCnInt64         = NativeInt;
{$ELSE}
  {$IFDEF SUPPORT_UINT64}
  TCnUInt64        = UInt64;
  {$ELSE}
TCnUInt64 = packed record  // 只能用这样的结构代替
  case boolean of
    True: (Value: int64);
    False: (Lo32, Hi32: cardinal);
end;
  {$ENDIF}
TCnInt64 = int64;
{$ENDIF}
 
// TUInt64 用于 cnvcl 库中不支持 UInt64 的运算如 div mod 等
{$IFDEF SUPPORT_UINT64}
  TUInt64          = UInt64;
  {$IFNDEF SUPPORT_PUINT64}
  PUInt64          = ^UInt64;
  {$ENDIF}
{$ELSE}
TUInt64 = int64;
PUInt64 = ^TUInt64;
{$ENDIF}
 
{$IFNDEF SUPPORT_INT64ARRAY}
// 如果系统没有定义 Int64Array
Int64Array  = array[0..$0FFFFFFE] of int64;
PInt64Array = ^Int64Array;
{$ENDIF}
 
TUInt64Array = array of TUInt64;
// 这个动态数组声明似乎容易和静态数组声明有冲突
 
ExtendedArray  = array[0..65537] of extended;
PExtendedArray = ^ExtendedArray;
 
PCnWord16Array = ^TCnWord16Array;
TCnWord16Array = array [0..0] of word;
 
{$IFDEF POSIX64}
  TCnLongWord32 = Cardinal; // Linux64/MacOS64 (or POSIX64?) LongWord is 64 Bits
{$ELSE}
TCnLongWord32 = longword;
{$ENDIF}
PCnLongWord32 = ^TCnLongWord32;
 
TCnLongWord32Array = array [0..MaxInt div SizeOf(integer) - 1] of TCnLongWord32;
 
PCnLongWord32Array = ^TCnLongWord32Array;
 
{$IFNDEF TBYTES_DEFINED}
TBytes = array of byte;
{* 无符号字节动态数组,未定义时定义上}
{$ENDIF}
 
TShortInts = array of shortint;
{* 有符号字节动态数组}
 
TSmallInts = array of smallint;
{* 有符号双字节动态数组}
 
TWords = array of word;
{* 无符号双字节动态数组}
 
TIntegers = array of integer;
{* 有符号四字节动态数组}
 
TCardinals = array of cardinal;
{* 无符号四字节动态数组}
 
PCnByte = ^byte;
PCnWord = ^word;
 
TCnBitOperation = (boAnd, boOr, boXor, boNot);
{* 位操作类型}
 
type
TCnMemSortCompareProc = function(p1, p2: Pointer; ElementByteSize: integer): integer;
{* 内存固定块尺寸的数组排序比较函数原型}
 
const
CN_MAX_SQRT_INT64: cardinal = 3037000499;
CN_MAX_INT64: int64     = $7FFFFFFFFFFFFFFF;
CN_MIN_INT64: int64     = $8000000000000000;
CN_MAX_UINT16: word     = $FFFF;
CN_MAX_UINT32: cardinal = $FFFFFFFF;
CN_MAX_TUINT64: TUInt64 = $FFFFFFFFFFFFFFFF;
CN_MAX_SIGNED_INT64_IN_TUINT64: TUInt64 = $7FFFFFFFFFFFFFFF;
 
{*
  对于 D567 等不支持 UInt64 的编译器,虽然可以用 Int64 代替 UInt64 进行加减、存储
  但乘除运算则无法直接完成,这里封装了两个调用 System 库中的 _lludiv 与 _llumod
  函数,实现以 Int64 表示的 UInt64 数据的 div 与 mod 功能。
}
function UInt64Mod(a, b: TUInt64): TUInt64;
{* 两个 UInt64 求余}
 
function UInt64Div(a, b: TUInt64): TUInt64;
{* 两个 UInt64 整除}
 
function UInt64Mul(a, b: cardinal): TUInt64;
{* 无符号 32 位整数不溢出的相乘,在不支持 UInt64 的平台上,结果以 UInt64 的形式放在 Int64 里,
  如果结果直接使用 Int64 计算则有可能溢出}
 
procedure UInt64AddUInt64(a, b: TUInt64; var ResLo, ResHi: TUInt64);
{* 两个无符号 64 位整数相加,处理溢出的情况,结果放 ResLo 与 ResHi 中
  注:内部实现按算法来看较为复杂,实际上如果溢出,ResHi 必然是 1,直接判断溢出并将其设 1 即可}
 
procedure UInt64MulUInt64(a, b: TUInt64; var ResLo, ResHi: TUInt64);
{* 两个无符号 64 位整数相乘,结果放 ResLo 与 ResHi 中,64 位下用汇编实现,提速约一倍以上}
 
function UInt64ToHex(N: TUInt64): string;
{* 将 UInt64 转换为十六进制字符串}
 
function UInt64ToStr(N: TUInt64): string;
{* 将 UInt64 转换为字符串}
 
function StrToUInt64(const S: string): TUInt64;
{* 将字符串转换为 UInt64}
 
function UInt64Compare(a, b: TUInt64): integer;
{* 比较两个 UInt64 值,分别根据 > = < 返回 1、0、-1}
 
function UInt64Sqrt(N: TUInt64): TUInt64;
{* 求 UInt64 的平方根的整数部分}
 
function UInt32IsNegative(N: cardinal): boolean;
{* 该 Cardinal 被当成 Integer 时是否小于 0}
 
function UInt64IsNegative(N: TUInt64): boolean;
{* 该 UInt64 被当成 Int64 时是否小于 0}
 
procedure UInt64SetBit(var b: TUInt64; Index: integer);
{* 给 UInt64 的某一位置 1,位 Index 从 0 开始}
 
procedure UInt64ClearBit(var b: TUInt64; Index: integer);
{* 给 UInt64 的某一位置 0,位 Index 从 0 开始}
 
function GetUInt64BitSet(b: TUInt64; Index: integer): boolean;
{* 返回 UInt64 的某一位是否是 1,位 Index 从 0 开始}
 
function GetUInt64HighBits(b: TUInt64): integer;
{* 返回 UInt64 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1}
 
function GetUInt32HighBits(b: cardinal): integer;
{* 返回 Cardinal 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1}
 
function GetUInt16HighBits(b: word): integer;
{* 返回 Word 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1}
 
function GetUInt8HighBits(b: byte): integer;
{* 返回 Byte 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1}
 
function GetUInt64LowBits(b: TUInt64): integer;
{* 返回 Int64 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1}
 
function GetUInt32LowBits(b: cardinal): integer;
{* 返回 Cardinal 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1}
 
function GetUInt16LowBits(b: word): integer;
{* 返回 Word 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1}
 
function GetUInt8LowBits(b: byte): integer;
{* 返回 Byte 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1}
 
function Int64Mod(M, N: int64): int64;
{* 封装的 Int64 Mod,M 碰到负值时取反求模再模减,但 N 仍要求正数否则结果不靠谱}
 
function IsUInt32PowerOf2(N: cardinal): boolean;
{* 判断一 32 位无符号整数是否 2 的整数次幂}
 
function IsUInt64PowerOf2(N: TUInt64): boolean;
{* 判断一 64 位无符号整数是否 2 的整数次幂}
 
function GetUInt32PowerOf2GreaterEqual(N: cardinal): cardinal;
{* 得到一比指定 32 位无符号整数数大或等的 2 的整数次幂,如溢出则返回 0}
 
function GetUInt64PowerOf2GreaterEqual(N: TUInt64): TUInt64;
{* 得到一比指定 64 位无符号整数数大或等的 2 的整数次幂,如溢出则返回 0}
 
function IsInt32AddOverflow(a, b: integer): boolean;
{* 判断两个 32 位有符号数相加是否溢出 32 位有符号上限}
 
function IsUInt32AddOverflow(a, b: cardinal): boolean;
{* 判断两个 32 位无符号数相加是否溢出 32 位无符号上限}
 
function IsInt64AddOverflow(a, b: int64): boolean;
{* 判断两个 64 位有符号数相加是否溢出 64 位有符号上限}
 
function IsUInt64AddOverflow(a, b: TUInt64): boolean;
{* 判断两个 64 位无符号数相加是否溢出 64 位无符号上限}
 
procedure UInt64Add(var r: TUInt64; a, b: TUInt64; out Carry: integer);
{* 两个 64 位无符号数相加,A + B => R,如果有溢出,则溢出的 1 搁进位标记里,否则清零}
 
procedure UInt64Sub(var r: TUInt64; a, b: TUInt64; out Carry: integer);
{* 两个 64 位无符号数相减,A - B => R,如果不够减有借位,则借的 1 搁借位标记里,否则清零}
 
function IsInt32MulOverflow(a, b: integer): boolean;
{* 判断两个 32 位有符号数相乘是否溢出 32 位有符号上限}
 
function IsUInt32MulOverflow(a, b: cardinal): boolean;
{* 判断两个 32 位无符号数相乘是否溢出 32 位无符号上限}
 
function IsUInt32MulOverflowInt64(a, b: cardinal; out r: TUInt64): boolean;
{* 判断两个 32 位无符号数相乘是否溢出 64 位有符号数,如未溢出也即返回 False 时,R 中直接返回结果
  如溢出也即返回 True,外界需要重新调用 UInt64Mul 才能实施相乘}
 
function IsInt64MulOverflow(a, b: int64): boolean;
{* 判断两个 64 位有符号数相乘是否溢出 64 位有符号上限}
 
function PointerToInteger(P: Pointer): integer;
{* 指针类型转换成整型,支持 32/64 位,注意 64 位下可能会丢超出 32 位的内容}
 
function IntegerToPointer(i: integer): Pointer;
{* 整型转换成指针类型,支持 32/64 位}
 
function Int64NonNegativeAddMod(a, b, N: int64): int64;
{* 求 Int64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0}
 
function UInt64NonNegativeAddMod(a, b, N: TUInt64): TUInt64;
{* 求 UInt64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0}
 
function Int64NonNegativeMulMod(a, b, N: int64): int64;
{* Int64 范围内的相乘求余,不能直接计算,容易溢出。要求 N 大于 0}
 
function UInt64NonNegativeMulMod(a, b, N: TUInt64): TUInt64;
{* UInt64 范围内的相乘求余,不能直接计算,容易溢出。}
 
function Int64NonNegativeMod(N: int64; P: int64): int64;
{* 封装的 Int64 非负求余函数,也就是余数为负时,加个除数变正,调用者需保证 P 大于 0}
 
function Int64NonNegativPower(N: int64; Exp: integer): int64;
{* Int64 的非负整数指数幂,不考虑溢出的情况}
 
function Int64NonNegativeRoot(N: int64; Exp: integer): int64;
{* 求 Int64 的非负整数次方根的整数部分,不考虑溢出的情况}
 
function UInt64NonNegativPower(N: TUInt64; Exp: integer): TUInt64;
{* UInt64 的非负整数指数幂,不考虑溢出的情况}
 
function UInt64NonNegativeRoot(N: TUInt64; Exp: integer): TUInt64;
{* 求 UInt64 的非负整数次方根的整数部分,不考虑溢出的情况}
 
function CurrentByteOrderIsBigEndian: boolean;
{* 返回当前运行期环境是否是大端,也就是是否将整数中的高序字节存储在较低的起始地址,符合从左到右的阅读习惯,如部分指定的 ARM 和 MIPS}
 
function CurrentByteOrderIsLittleEndian: boolean;
{* 返回当前运行期环境是否是小端,也就是是否将整数中的高序字节存储在较高的起始地址,如 x86 与部分默认 arm}
 
function Int64ToBigEndian(Value: int64): int64;
{* 确保 Int64 值为大端,在小端环境中会进行转换}
 
function Int32ToBigEndian(Value: integer): integer;
{* 确保 Int32 值为大端,在小端环境中会进行转换}
 
function Int16ToBigEndian(Value: smallint): smallint;
{* 确保 Int16 值为大端,在小端环境中会进行转换}
 
function Int64ToLittleEndian(Value: int64): int64;
{* 确保 Int64 值为小端,在大端环境中会进行转换}
 
function Int32ToLittleEndian(Value: integer): integer;
{* 确保 Int32 值为小端,在大端环境中会进行转换}
 
function Int16ToLittleEndian(Value: smallint): smallint;
{* 确保 Int16 值为小端,在大端环境中会进行转换}
 
function UInt64ToBigEndian(Value: TUInt64): TUInt64;
{* 确保 UInt64 值为大端,在小端环境中会进行转换}
 
function UInt32ToBigEndian(Value: cardinal): cardinal;
{* 确保 UInt32 值为大端,在小端环境中会进行转换}
 
function UInt16ToBigEndian(Value: word): word;
{* 确保 UInt16 值为大端,在小端环境中会进行转换}
 
function UInt64ToLittleEndian(Value: TUInt64): TUInt64;
{* 确保 UInt64 值为小端,在大端环境中会进行转换}
 
function UInt32ToLittleEndian(Value: cardinal): cardinal;
{* 确保 UInt32 值为小端,在大端环境中会进行转换}
 
function UInt16ToLittleEndian(Value: word): word;
{* 确保 UInt16 值为小端,在大端环境中会进行转换}
 
function Int64HostToNetwork(Value: int64): int64;
{* 将 Int64 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换}
 
function Int32HostToNetwork(Value: integer): integer;
{* 将 Int32 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换}
 
function Int16HostToNetwork(Value: smallint): smallint;
{* 将 Int16 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换}
 
function Int64NetworkToHost(Value: int64): int64;
{* 将 Int64 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换}
 
function Int32NetworkToHost(Value: integer): integer;
{* 将 Int32值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换}
 
function Int16NetworkToHost(Value: smallint): smallint;
{* 将 Int16 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换}
 
function UInt64HostToNetwork(Value: TUInt64): TUInt64;
{* 将 UInt64 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换}
 
function UInt32HostToNetwork(Value: cardinal): cardinal;
{* 将 UInt32 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换}
 
function UInt16HostToNetwork(Value: word): word;
{* 将 UInt16 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换}
 
function UInt64NetworkToHost(Value: TUInt64): TUInt64;
{* 将 UInt64 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换}
 
function UInt32NetworkToHost(Value: cardinal): cardinal;
{* 将 UInt32值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换}
 
function UInt16NetworkToHost(Value: word): word;
{* 将 UInt16 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换}
 
procedure MemoryNetworkToHost(AMem: Pointer; MemByteLen: integer);
{* 将一片内存区域从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换,
  该方法应用场合较少,大多二/四/八字节转换已经足够}
 
procedure MemoryHostToNetwork(AMem: Pointer; MemByteLen: integer);
{* 将一片内存区域从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换,
  该方法应用场合较少,大多二/四/八字节转换已经足够}
 
procedure ReverseMemory(AMem: Pointer; MemByteLen: integer);
{* 按字节顺序倒置一块内存块,字节内部不变}
 
function ReverseBitsInInt8(V: byte): byte;
{* 倒置一字节内部的位的内容}
 
function ReverseBitsInInt16(V: word): word;
{* 倒置二字节及其内部位的内容}
 
function ReverseBitsInInt32(V: cardinal): cardinal;
{* 倒置四字节及其内部位的内容}
 
function ReverseBitsInInt64(V: int64): int64;
{* 倒置八字节及其内部位的内容}
 
procedure ReverseMemoryWithBits(AMem: Pointer; MemByteLen: integer);
{* 按字节顺序倒置一块内存块,并且每个字节也倒过来}
 
procedure MemoryAnd(AMem, BMem: Pointer; MemByteLen: integer; ResMem: Pointer);
{* 两块长度相同的内存 AMem 和 BMem 按位与,结果放 ResMem 中,三者可相同}
 
procedure MemoryOr(AMem, BMem: Pointer; MemByteLen: integer; ResMem: Pointer);
{* 两块长度相同的内存 AMem 和 BMem 按位或,结果放 ResMem 中,三者可相同}
 
procedure MemoryXor(AMem, BMem: Pointer; MemByteLen: integer; ResMem: Pointer);
{* 两块长度相同的内存 AMem 和 BMem 按位异或,结果放 ResMem 中,三者可相同}
 
procedure MemoryNot(AMem: Pointer; MemByteLen: integer; ResMem: Pointer);
{* 一块内存 AMem 取反,结果放 ResMem 中,两者可相同}
 
procedure MemoryShiftLeft(AMem, BMem: Pointer; MemByteLen: integer; BitCount: integer);
{* AMem 整块内存左移 BitCount 位至 BMem,往内存地址低位移,空位补 0,两者可相等}
 
procedure MemoryShiftRight(AMem, BMem: Pointer; MemByteLen: integer; BitCount: integer);
{* AMem 整块内存右移 BitCount 位至 BMem,往内存地址高位移,空位补 0,两者可相等}
 
function MemoryIsBitSet(AMem: Pointer; N: integer): boolean;
{* 返回内存块某 Bit 位是否置 1,内存地址低位是 0,字节内还是右边为 0}
 
procedure MemorySetBit(AMem: Pointer; N: integer);
{* 给内存块某 Bit 位置 1,内存地址低位是 0,字节内还是右边为 0}
 
procedure MemoryClearBit(AMem: Pointer; N: integer);
{* 给内存块某 Bit 位置 0,内存地址低位是 0,字节内还是右边为 0}
 
function MemoryToBinStr(AMem: Pointer; MemByteLen: integer;
Sep: boolean = False): string;
{* 将一块内存内容从低到高字节顺序输出为二进制字符串,Sep 表示是否空格分隔}
 
procedure MemorySwap(AMem, BMem: Pointer; MemByteLen: integer);
{* 交换两块相同长度的内存块的内容,如两者是相同的内存块则什么都不做}
 
function MemoryCompare(AMem, BMem: Pointer; MemByteLen: integer): integer;
{* 以无符号数的方式比较两块内存,返回 1、0、-1,如两者是相同的内存块则直接返回 0}
 
procedure MemoryQuickSort(Mem: Pointer; ElementByteSize: integer;
ElementCount: integer; CompareProc: TCnMemSortCompareProc = nil);
{* 针对固定大小的元素的数组进行排序}
 
function UInt8ToBinStr(V: byte): string;
{* 将一无符号字节转换为二进制字符串}
 
function UInt16ToBinStr(V: word): string;
{* 将一无符号字转换为二进制字符串}
 
function UInt32ToBinStr(V: cardinal): string;
{* 将一四字节无符号整数转换为二进制字符串}
 
function UInt32ToStr(V: cardinal): string;
{* 将一四字节无符号整数转换为字符串}
 
function UInt64ToBinStr(V: TUInt64): string;
{* 将一无符号 64 字节整数转换为二进制字符串}
 
function HexToInt(const Hex: string): integer; overload;
{* 将一十六进制字符串转换为整型,适合较短尤其是 2 字符的字符串}
 
function HexToInt(Hex: PChar; CharLen: integer): integer; overload;
{* 将一十六进制字符串指针所指的内容转换为整型,适合较短尤其是 2 字符的字符串}
 
function IsHexString(const Hex: string): boolean;
{* 判断一字符串是否合法的十六进制字符串,不区分大小写}
 
function DataToHex(InData: Pointer; ByteLength: integer;
UseUpperCase: boolean = True): string;
{* 内存块转换为十六进制字符串,内存低位的内容出现在字符串左方,相当于网络字节顺序,
  UseUpperCase 控制输出内容的大小写}
 
function HexToData(const Hex: string; OutData: Pointer = nil): integer;
{* 十六进制字符串转换为内存块,字符串左方的内容出现在内存低位,相当于网络字节顺序,
  十六进制字符串长度为奇或转换失败时抛出异常。返回转换成功的字节数
  注意 OutData 应该指向足够容纳转换内容的区域,长度至少为 Length(Hex) div 2
  如果传 nil,则只返回所需的字节长度,不进行正式转换}
 
function StringToHex(const Data: string; UseUpperCase: boolean = True): string;
{* 字符串转换为十六进制字符串,UseUpperCase 控制输出内容的大小写}
 
function HexToString(const Hex: string): string;
{* 十六进制字符串转换为字符串,十六进制字符串长度为奇或转换失败时抛出异常}
 
function HexToAnsiStr(const Hex: ansistring): ansistring;
{* 十六进制字符串转换为字符串,十六进制字符串长度为奇或转换失败时抛出异常}
 
function AnsiStrToHex(const Data: ansistring; UseUpperCase: boolean = True): ansistring;
{* AnsiString 转换为十六进制字符串,UseUpperCase 控制输出内容的大小写}
 
function BytesToHex(Data: TBytes; UseUpperCase: boolean = True): string;
{* 字节数组转换为十六进制字符串,下标低位的内容出现在字符串左方,相当于网络字节顺序,
  UseUpperCase 控制输出内容的大小写}
 
function HexToBytes(const Hex: string): TBytes;
{* 十六进制字符串转换为字节数组,字符串左边的内容出现在下标低位,相当于网络字节顺序,
  字符串长度为奇或转换失败时抛出异常}
 
function StreamToHex(Stream: TStream; UseUpperCase: boolean = True): string;
{* 将流中的全部内容从头转换为十六进制字符串}
 
function HexToStream(const Hex: string; Stream: TStream): integer;
{* 将十六进制字符串内容转换后写入流中,返回写入的字节数}
 
procedure ReverseBytes(Data: TBytes);
{* 按字节顺序倒置一字节数组}
 
function StreamToBytes(Stream: TStream): TBytes;
{* 从流从头读入全部内容至字节数组,返回创建的字节数组}
 
function BytesToStream(Data: TBytes; OutStream: TStream): integer;
{* 字节数组写入整个流,返回写入字节数}
 
function AnsiToBytes(const str: ansistring): TBytes;
{* 将 AnsiString 的内容转换为字节数组,不处理编码}
 
function BytesToAnsi(const Data: TBytes): ansistring;
{* 将字节数组的内容转换为 AnsiString,不处理编码}
 
function BytesToString(const Data: TBytes): string;
{* 将字节数组的内容转换为 string,内部逐个赋值,不处理编码}
 
function MemoryToString(Mem: Pointer; MemByteLen: integer): string;
{* 将内存块的内容转换为 string,内部逐个赋值,不处理编码}
 
function ConcatBytes(a, b: TBytes): TBytes;
{* 将 A B 两个字节数组顺序拼好返回一个新字节数组,A B 保持不变}
 
function NewBytesFromMemory(Data: Pointer; DataByteLen: integer): TBytes;
{* 新建一字节数组,并从一片内存区域复制内容过来。}
 
function CompareBytes(a, b: TBytes): boolean;
{* 比较两个字节数组内容是否相同}
 
procedure MoveMost(const Source; var Dest; ByteLen, MostLen: integer);
{* 从 Source 移动 ByteLen 且不超过 MostLen 个字节到 Dest 中,
  如 ByteLen 小于 MostLen,则 Dest 填充 0,要求 Dest 容纳至少 MostLen}
 
// ================ 以下是执行时间固定的无 if 判断的部分逻辑函数 ===============
 
procedure ConstTimeConditionalSwap8(CanSwap: boolean; var a, b: byte);
{* 针对两个字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换}
 
procedure ConstTimeConditionalSwap16(CanSwap: boolean; var a, b: word);
{* 针对两个双字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换}
 
procedure ConstTimeConditionalSwap32(CanSwap: boolean; var a, b: cardinal);
{* 针对两个四字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换}
 
procedure ConstTimeConditionalSwap64(CanSwap: boolean; var a, b: TUInt64);
{* 针对两个八字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换}
 
function ConstTimeEqual8(a, b: byte): boolean;
{* 针对俩单字节的执行时间固定的比较,避免 CPU 指令跳转预测导致的执行时间差异,内容相同时返回 True}
 
function ConstTimeEqual16(a, b: word): boolean;
{* 针对俩双字节的执行时间固定的比较,避免 CPU 指令跳转预测导致的执行时间差异,内容相同时返回 True}
 
function ConstTimeEqual32(a, b: cardinal): boolean;
{* 针对俩四字节的执行时间固定的比较,避免 CPU 指令跳转预测导致的执行时间差异,内容相同时返回 True}
 
function ConstTimeEqual64(a, b: TUInt64): boolean;
{* 针对俩八字节的执行时间固定的比较,避免 CPU 指令跳转预测导致的执行时间差异,内容相同时返回 True}
 
function ConstTimeBytesEqual(a, b: TBytes): boolean;
{* 针对俩相同长度的字节数组的执行时间固定的比较,内容相同时返回 True}
 
function ConstTimeExpandBoolean8(V: boolean): byte;
{* 根据 V 的值返回一字节全 1 或全 0}
 
function ConstTimeExpandBoolean16(V: boolean): word;
{* 根据 V 的值返回俩字节全 1 或全 0}
 
function ConstTimeExpandBoolean32(V: boolean): cardinal;
{* 根据 V 的值返回四字节全 1 或全 0}
 
function ConstTimeExpandBoolean64(V: boolean): TUInt64;
{* 根据 V 的值返回八字节全 1 或全 0}
 
function ConstTimeConditionalSelect8(Condition: boolean; a, b: byte): byte;
{* 针对两个字节变量执行时间固定的判断选择,Condtion 为 True 时返回 A,否则返回 B}
 
function ConstTimeConditionalSelect16(Condition: boolean; a, b: word): word;
{* 针对两个双字节变量执行时间固定的判断选择,Condtion 为 True 时返回 A,否则返回 B}
 
function ConstTimeConditionalSelect32(Condition: boolean; a, b: cardinal): cardinal;
{* 针对两个四字节变量执行时间固定的判断选择,Condtion 为 True 时返回 A,否则返回 B}
 
function ConstTimeConditionalSelect64(Condition: boolean; a, b: TUInt64): TUInt64;
{* 针对两个八字节变量执行时间固定的判断选择,Condtion 为 True 时返回 A,否则返回 B}
 
// ================ 以上是执行时间固定的无 if 判断的部分逻辑函数 ===============
 
{$IFDEF MSWINDOWS}
 
// 这四个函数因为用了 Intel 汇编,因而只支持 32 位和 64 位的 Intel CPU,照理应该用条件:CPUX86 或 CPUX64
 
procedure Int64DivInt32Mod(a: int64; b: integer; var DivRes, ModRes: integer);
{* 64 位有符号数除以 32 位有符号数,商放 DivRes,余数放 ModRes
  调用者须自行保证商在 32 位范围内,否则会抛溢出异常}
 
procedure UInt64DivUInt32Mod(a: TUInt64; b: cardinal; var DivRes, ModRes: cardinal);
{* 64 位无符号数除以 32 位无符号数,商放 DivRes,余数放 ModRes
  调用者须自行保证商在 32 位范围内,否则会抛溢出异常}
 
procedure Int128DivInt64Mod(ALo, AHi: int64; b: int64; var DivRes, ModRes: int64);
{* 128 位有符号数除以 64 位有符号数,商放 DivRes,余数放 ModRes
  调用者须自行保证商在 64 位范围内,否则会抛溢出异常}
 
procedure UInt128DivUInt64Mod(ALo, AHi: TUInt64; b: TUInt64;
var DivRes, ModRes: TUInt64);
{* 128 位无符号数除以 64 位无符号数,商放 DivRes,余数放 ModRes
  调用者须自行保证商在 64 位范围内,否则会抛溢出异常}
 
{$ENDIF}
 
function IsUInt128BitSet(Lo, Hi: TUInt64; N: integer): boolean;
{* 针对两个 Int64 拼成的 128 位数字,返回第 N 位是否为 1,N 从 0 到 127}
 
procedure SetUInt128Bit(var Lo, Hi: TUInt64; N: integer);
{* 针对两个 Int64 拼成的 128 位数字,设置第 N 位为 1,N 从 0 到 127}
 
procedure ClearUInt128Bit(var Lo, Hi: TUInt64; N: integer);
{* 针对两个 Int64 拼成的 128 位数字,清掉第 N 位,N 从 0 到 127}
 
function UnsignedAddWithLimitRadix(a, b, c: cardinal; var r: cardinal;
L, H: cardinal): cardinal;
{* 计算非正常进制的无符号加法,A + B + C,结果放 R 中,返回进位值
  结果确保在 L 和 H 的闭区间内,用户须确保 H 大于 L,不考虑溢出的情形
  该函数多用于字符分区间计算与映射,其中 C 一般是进位}
 
{$IFDEF COMPILER5}
 
function BoolToStr(Value: Boolean; UseBoolStrs: Boolean = False): string;
{* Delphi 5 下没有该函数,补上}
 
{$ENDIF}
 
implementation
 
uses
CnFloat;
 
var
FByteOrderIsBigEndian: boolean = False;
 
function CurrentByteOrderIsBigEndian: boolean;
type
  TByteOrder = packed record
    case boolean of
      False: (c: array[0..1] of byte);
      True: (W: word);
    end;
var
  T: TByteOrder;
begin
  T.W    := $00CC;
  Result := T.c[1] = $CC;
end;
 
function CurrentByteOrderIsLittleEndian: boolean;
begin
  Result := not CurrentByteOrderIsBigEndian;
end;
 
function ReverseInt64(Value: int64): int64;
var
  Lo, Hi: cardinal;
  Rec: Int64Rec;
begin
  Lo     := Int64Rec(Value).Lo;
  Hi     := Int64Rec(Value).Hi;
  Lo     := ((Lo and $000000FF) shl 24) or ((Lo and $0000FF00) shl 8) or
    ((Lo and $00FF0000) shr 8) or ((Lo and $FF000000) shr 24);
  Hi     := ((Hi and $000000FF) shl 24) or ((Hi and $0000FF00) shl 8) or
    ((Hi and $00FF0000) shr 8) or ((Hi and $FF000000) shr 24);
  Rec.Lo := Hi;
  Rec.Hi := Lo;
  Result := int64(Rec);
end;
 
function ReverseUInt64(Value: TUInt64): TUInt64;
var
  Lo, Hi: cardinal;
  Rec: Int64Rec;
begin
  Lo     := Int64Rec(Value).Lo;
  Hi     := Int64Rec(Value).Hi;
  Lo     := ((Lo and $000000FF) shl 24) or ((Lo and $0000FF00) shl 8) or
    ((Lo and $00FF0000) shr 8) or ((Lo and $FF000000) shr 24);
  Hi     := ((Hi and $000000FF) shl 24) or ((Hi and $0000FF00) shl 8) or
    ((Hi and $00FF0000) shr 8) or ((Hi and $FF000000) shr 24);
  Rec.Lo := Hi;
  Rec.Hi := Lo;
  Result := TUInt64(Rec);
end;
 
function Int64ToBigEndian(Value: int64): int64;
begin
  if FByteOrderIsBigEndian then
    Result := Value
  else
    Result := ReverseInt64(Value);
end;
 
function Int32ToBigEndian(Value: integer): integer;
begin
  if FByteOrderIsBigEndian then
    Result := Value
  else
    Result := integer((Value and $000000FF) shl 24) or integer(
      (Value and $0000FF00) shl 8) or integer((Value and $00FF0000) shr 8) or
      integer((Value and $FF000000) shr 24);
end;
 
function Int16ToBigEndian(Value: smallint): smallint;
begin
  if FByteOrderIsBigEndian then
    Result := Value
  else
    Result := smallint((Value and $00FF) shl 8) or smallint((Value and $FF00) shr 8);
end;
 
function Int64ToLittleEndian(Value: int64): int64;
begin
  if not FByteOrderIsBigEndian then
    Result := Value
  else
    Result := ReverseInt64(Value);
end;
 
function Int32ToLittleEndian(Value: integer): integer;
begin
  if not FByteOrderIsBigEndian then
    Result := Value
  else
    Result := integer((Value and $000000FF) shl 24) or integer(
      (Value and $0000FF00) shl 8) or integer((Value and $00FF0000) shr 8) or
      integer((Value and $FF000000) shr 24);
end;
 
function Int16ToLittleEndian(Value: smallint): smallint;
begin
  if not FByteOrderIsBigEndian then
    Result := Value
  else
    Result := smallint((Value and $00FF) shl 8) or smallint((Value and $FF00) shr 8);
end;
 
function UInt64ToBigEndian(Value: TUInt64): TUInt64;
begin
  if FByteOrderIsBigEndian then
    Result := Value
  else
    Result := ReverseUInt64(Value);
end;
 
function UInt32ToBigEndian(Value: cardinal): cardinal;
begin
  if FByteOrderIsBigEndian then
    Result := Value
  else
    Result := cardinal((Value and $000000FF) shl 24) or cardinal(
      (Value and $0000FF00) shl 8) or cardinal((Value and $00FF0000) shr 8) or
      cardinal((Value and $FF000000) shr 24);
end;
 
function UInt16ToBigEndian(Value: word): word;
begin
  if FByteOrderIsBigEndian then
    Result := Value
  else
    Result := word((Value and $00FF) shl 8) or word((Value and $FF00) shr 8);
end;
 
function UInt64ToLittleEndian(Value: TUInt64): TUInt64;
begin
  if not FByteOrderIsBigEndian then
    Result := Value
  else
    Result := ReverseUInt64(Value);
end;
 
function UInt32ToLittleEndian(Value: cardinal): cardinal;
begin
  if not FByteOrderIsBigEndian then
    Result := Value
  else
    Result := cardinal((Value and $000000FF) shl 24) or cardinal(
      (Value and $0000FF00) shl 8) or cardinal((Value and $00FF0000) shr 8) or
      cardinal((Value and $FF000000) shr 24);
end;
 
function UInt16ToLittleEndian(Value: word): word;
begin
  if not FByteOrderIsBigEndian then
    Result := Value
  else
    Result := word((Value and $00FF) shl 8) or word((Value and $FF00) shr 8);
end;
 
function Int64HostToNetwork(Value: int64): int64;
begin
  if not FByteOrderIsBigEndian then
    Result := ReverseInt64(Value)
  else
    Result := Value;
end;
 
function Int32HostToNetwork(Value: integer): integer;
begin
  if not FByteOrderIsBigEndian then
    Result := integer((Value and $000000FF) shl 24) or integer(
      (Value and $0000FF00) shl 8) or integer((Value and $00FF0000) shr 8) or
      integer((Value and $FF000000) shr 24)
  else
    Result := Value;
end;
 
function Int16HostToNetwork(Value: smallint): smallint;
begin
  if not FByteOrderIsBigEndian then
    Result := smallint((Value and $00FF) shl 8) or smallint((Value and $FF00) shr 8)
  else
    Result := Value;
end;
 
function Int64NetworkToHost(Value: int64): int64;
begin
  if not FByteOrderIsBigEndian then
    Result := ReverseInt64(Value)
  else
    Result := Value;
end;
 
function Int32NetworkToHost(Value: integer): integer;
begin
  if not FByteOrderIsBigEndian then
    Result := integer((Value and $000000FF) shl 24) or integer(
      (Value and $0000FF00) shl 8) or integer((Value and $00FF0000) shr 8) or
      integer((Value and $FF000000) shr 24)
  else
    Result := Value;
end;
 
function Int16NetworkToHost(Value: smallint): smallint;
begin
  if not FByteOrderIsBigEndian then
    Result := smallint((Value and $00FF) shl 8) or smallint((Value and $FF00) shr 8)
  else
    Result := Value;
end;
 
function UInt64HostToNetwork(Value: TUInt64): TUInt64;
begin
  if CurrentByteOrderIsBigEndian then
    Result := Value
  else
    Result := ReverseUInt64(Value);
end;
 
function UInt32HostToNetwork(Value: cardinal): cardinal;
begin
  if not FByteOrderIsBigEndian then
    Result := cardinal((Value and $000000FF) shl 24) or cardinal(
      (Value and $0000FF00) shl 8) or cardinal((Value and $00FF0000) shr 8) or
      cardinal((Value and $FF000000) shr 24)
  else
    Result := Value;
end;
 
function UInt16HostToNetwork(Value: word): word;
begin
  if not FByteOrderIsBigEndian then
    Result := ((Value and $00FF) shl 8) or ((Value and $FF00) shr 8)
  else
    Result := Value;
end;
 
function UInt64NetworkToHost(Value: TUInt64): TUInt64;
begin
  if CurrentByteOrderIsBigEndian then
    Result := Value
  else
    Result := ReverseUInt64(Value);
end;
 
function UInt32NetworkToHost(Value: cardinal): cardinal;
begin
  if not FByteOrderIsBigEndian then
    Result := cardinal((Value and $000000FF) shl 24) or cardinal(
      (Value and $0000FF00) shl 8) or cardinal((Value and $00FF0000) shr 8) or
      cardinal((Value and $FF000000) shr 24)
  else
    Result := Value;
end;
 
function UInt16NetworkToHost(Value: word): word;
begin
  if not FByteOrderIsBigEndian then
    Result := ((Value and $00FF) shl 8) or ((Value and $FF00) shr 8)
  else
    Result := Value;
end;
 
function ReverseBitsInInt8(V: byte): byte;
begin
  // 0 和 1 交换、2 和 3 交换、4 和 5 交换、6 和 7 交换
  V      := ((V and $AA) shr 1) or ((V and $55) shl 1);
  // 01 和 23 交换、45 和 67 交换
  V      := ((V and $CC) shr 2) or ((V and $33) shl 2);
  // 0123 和 4567 交换
  V      := (V shr 4) or (V shl 4);
  Result := V;
end;
 
function ReverseBitsInInt16(V: word): word;
begin
  Result := (ReverseBitsInInt8(V and $00FF) shl 8) or ReverseBitsInInt8(
    (V and $FF00) shr 8);
end;
 
function ReverseBitsInInt32(V: cardinal): cardinal;
begin
  Result := (ReverseBitsInInt16(V and $0000FFFF) shl 16) or
    ReverseBitsInInt16((V and $FFFF0000) shr 16);
end;
 
function ReverseBitsInInt64(V: int64): int64;
begin
  Result := (int64(ReverseBitsInInt32(V and $00000000FFFFFFFF)) shl 32) or
    ReverseBitsInInt32((V and $FFFFFFFF00000000) shr 32);
end;
 
procedure ReverseMemory(AMem: Pointer; MemByteLen: integer);
var
  i, L: integer;
  P: PByteArray;
  T: byte;
begin
  if (AMem = nil) or (MemByteLen < 2) then
    Exit;
 
  L := MemByteLen div 2;
  P := PByteArray(AMem);
  for i := 0 to L - 1 do
    begin
    // 交换第 I 和第 MemLen - I - 1
    T     := P^[i];
    P^[i] := P^[MemByteLen - i - 1];
    P^[MemByteLen - i - 1] := T;
    end;
end;
 
procedure ReverseMemoryWithBits(AMem: Pointer; MemByteLen: integer);
var
  i: integer;
  P: PByteArray;
begin
  if (AMem = nil) or (MemByteLen <= 0) then
    Exit;
 
  ReverseMemory(AMem, MemByteLen);
  P := PByteArray(AMem);
 
  for i := 0 to MemByteLen - 1 do
    P^[i] := ReverseBitsInInt8(P^[i]);
end;
 
procedure MemoryNetworkToHost(AMem: Pointer; MemByteLen: integer);
begin
  if not FByteOrderIsBigEndian then
    ReverseMemory(AMem, MemByteLen);
end;
 
procedure MemoryHostToNetwork(AMem: Pointer; MemByteLen: integer);
begin
  if not FByteOrderIsBigEndian then
    ReverseMemory(AMem, MemByteLen);
end;
 
// N 字节长度的内存块的位操作
procedure MemoryBitOperation(AMem, BMem, RMem: Pointer; N: integer; Op: TCnBitOperation);
var
  a, b, r: PCnLongWord32Array;
  BA, BB, BR: PByteArray;
begin
  if N <= 0 then
    Exit;
 
  if (AMem = nil) or ((BMem = nil) and (Op <> boNot)) or (RMem = nil) then
    Exit;
 
  a := PCnLongWord32Array(AMem);
  b := PCnLongWord32Array(BMem);
  r := PCnLongWord32Array(RMem);
 
  while (N and (not 3)) <> 0 do
    begin
    case Op of
      boAnd:
        r^[0] := a^[0] and b^[0];
      boOr:
        r^[0] := a^[0] or b^[0];
      boXor:
        r^[0] := a^[0] xor b^[0];
      boNot: // 求反时忽略 B
        r^[0] := not a^[0];
      end;
 
    a := PCnLongWord32Array(TCnNativeInt(a) + SizeOf(cardinal));
    b := PCnLongWord32Array(TCnNativeInt(b) + SizeOf(cardinal));
    r := PCnLongWord32Array(TCnNativeInt(r) + SizeOf(cardinal));
 
    Dec(N, SizeOf(cardinal));
    end;
 
  if N > 0 then
    begin
    BA := PByteArray(a);
    BB := PByteArray(b);
    BR := PByteArray(r);
 
    while N <> 0 do
      begin
      case Op of
        boAnd:
          BR^[0] := BA^[0] and BB^[0];
        boOr:
          BR^[0] := BA^[0] or BB^[0];
        boXor:
          BR^[0] := BA^[0] xor BB^[0];
        boNot:
          BR^[0] := not BA^[0];
        end;
 
      BA := PByteArray(TCnNativeInt(BA) + SizeOf(byte));
      BB := PByteArray(TCnNativeInt(BB) + SizeOf(byte));
      BR := PByteArray(TCnNativeInt(BR) + SizeOf(byte));
      Dec(N);
      end;
    end;
end;
 
procedure MemoryAnd(AMem, BMem: Pointer; MemByteLen: integer; ResMem: Pointer);
begin
  MemoryBitOperation(AMem, BMem, ResMem, MemByteLen, boAnd);
end;
 
procedure MemoryOr(AMem, BMem: Pointer; MemByteLen: integer; ResMem: Pointer);
begin
  MemoryBitOperation(AMem, BMem, ResMem, MemByteLen, boOr);
end;
 
procedure MemoryXor(AMem, BMem: Pointer; MemByteLen: integer; ResMem: Pointer);
begin
  MemoryBitOperation(AMem, BMem, ResMem, MemByteLen, boXor);
end;
 
procedure MemoryNot(AMem: Pointer; MemByteLen: integer; ResMem: Pointer);
begin
  MemoryBitOperation(AMem, nil, ResMem, MemByteLen, boNot);
end;
 
procedure MemoryShiftLeft(AMem, BMem: Pointer; MemByteLen: integer; BitCount: integer);
var
  i, L, N, LB, RB: integer;
  PF, PT: PByteArray;
begin
  if (AMem = nil) or (MemByteLen <= 0) or (BitCount = 0) then
    Exit;
 
  if BitCount < 0 then
    begin
    MemoryShiftRight(AMem, BMem, MemByteLen, -BitCount);
    Exit;
    end;
 
  if BMem = nil then
    BMem := AMem;
 
  if (MemByteLen * 8) <= BitCount then // 移太多不够,全 0
    begin
    FillChar(BMem^, MemByteLen, 0);
    Exit;
    end;
 
  N  := BitCount div 8// 移位超过的整字节数
  RB := BitCount mod 8; // 去除整字节后剩下的位数
  LB := 8 - RB;         // 上面剩下的位数在一字节内再剩下的位数
 
  PF := PByteArray(AMem);
  PT := PByteArray(BMem);
 
  if RB = 0 then // 整块,好办,要移位的字节数是 MemLen - NW
    begin
    Move(PF^[N], PT^[0], MemByteLen - N);
    FillChar(PT^[MemByteLen - N], N, 0);
    end
  else
    begin
    // 起点是 PF^[N] 和 PT^[0],长度 MemLen - N 个字节,但相邻字节间有交叉
    L  := MemByteLen - N;
    PF := PByteArray(TCnNativeInt(PF) + N);
 
    for i := 1 to L do // 从低位往低移动,先处理低的
      begin
      PT^[0] := byte(PF^[0] shl RB);
      if i < L then    // 最高一个字节 PF^[1] 会超界
        PT^[0] := (PF^[1] shr LB) or PT^[0];
 
      PF := PByteArray(TCnNativeInt(PF) + 1);
      PT := PByteArray(TCnNativeInt(PT) + 1);
      end;
 
    // 剩下的要填 0
    if N > 0 then
      FillChar(PT^[0], N, 0);
    end;
end;
 
procedure MemoryShiftRight(AMem, BMem: Pointer; MemByteLen: integer; BitCount: integer);
var
  i, L, N, LB, RB: integer;
  PF, PT: PByteArray;
begin
  if (AMem = nil) or (MemByteLen <= 0) or (BitCount = 0) then
    Exit;
 
  if BitCount < 0 then
    begin
    MemoryShiftLeft(AMem, BMem, MemByteLen, -BitCount);
    Exit;
    end;
 
  if BMem = nil then
    BMem := AMem;
 
  if (MemByteLen * 8) <= BitCount then // 移太多不够,全 0
    begin
    FillChar(BMem^, MemByteLen, 0);
    Exit;
    end;
 
  N  := BitCount div 8// 移位超过的整字节数
  RB := BitCount mod 8; // 去除整字节后剩下的位数
  LB := 8 - RB;         // 上面剩下的位数在一字节内再剩下的位数
 
  if RB = 0 then // 整块,好办,要移位的字节数是 MemLen - N
    begin
    PF := PByteArray(AMem);
    PT := PByteArray(BMem);
 
    Move(PF^[0], PT^[N], MemByteLen - N);
    FillChar(PT^[0], N, 0);
    end
  else
    begin
    // 起点是 PF^[0] 和 PT^[N],长度 MemLen - N 个字节,但得从高处开始,且相邻字节间有交叉
    L := MemByteLen - N;
 
    PF := PByteArray(TCnNativeInt(AMem) + L - 1);
    PT := PByteArray(TCnNativeInt(BMem) + MemByteLen - 1);
 
    for i := L downto 1 do // 从高位往高位移动,先处理后面的
      begin
      PT^[0] := byte(PF^[0] shr RB);
      if i > 1 then        // 最低一个字节 PF^[-1] 会超界
        begin
        PF     := PByteArray(TCnNativeInt(PF) - 1);
        PT^[0] := (PF^[0] shl LB) or PT^[0];
        end
      else
        PF := PByteArray(TCnNativeInt(PF) - 1);
 
      PT := PByteArray(TCnNativeInt(PT) - 1);
      end;
 
    // 剩下的最前面的要填 0
    if N > 0 then
      FillChar(BMem^, N, 0);
    end;
end;
 
function MemoryIsBitSet(AMem: Pointer; N: integer): boolean;
var
  P: pbyte;
  a, b: integer;
  V: byte;
begin
  if (AMem = nil) or (N < 0) then
    raise Exception.Create(SRangeError);
 
  a := N div 8;
  b := N mod 8;
  P := pbyte(TCnNativeInt(AMem) + a);
 
  V      := byte(1 shl b);
  Result := (P^ and V) <> 0;
end;
 
procedure MemorySetBit(AMem: Pointer; N: integer);
var
  P: pbyte;
  a, b: integer;
  V: byte;
begin
  if (AMem = nil) or (N < 0) then
    raise Exception.Create(SRangeError);
 
  a := N div 8;
  b := N mod 8;
  P := pbyte(TCnNativeInt(AMem) + a);
 
  V  := byte(1 shl b);
  P^ := P^ or V;
end;
 
procedure MemoryClearBit(AMem: Pointer; N: integer);
var
  P: pbyte;
  a, b: integer;
  V: byte;
begin
  if (AMem = nil) or (N < 0) then
    raise Exception.Create(SRangeError);
 
  a := N div 8;
  b := N mod 8;
  P := pbyte(TCnNativeInt(AMem) + a);
 
  V  := not byte(1 shl b);
  P^ := P^ and V;
end;
 
function MemoryToBinStr(AMem: Pointer; MemByteLen: integer; Sep: boolean): string;
var
  j, L: integer;
  P: PByteArray;
  b: PChar;
 
procedure FillAByteToBuf(V: byte; Buf: PChar);
  const
    M = $80;
  var
    i: integer;
  begin
    for i := 0 to 7 do
      begin
      if (V and M) <> 0 then
        Buf[i] := '1'
      else
        Buf[i] := '0';
      V := V shl 1;
      end;
  end;
 
begin
  Result := '';
  if (AMem = nil) or (MemByteLen <= 0) then
    Exit;
 
  L := MemByteLen * 8;
  if Sep then
    L := L + MemByteLen - 1; // 中间用空格分隔
 
  setlength(Result, L);
  b := PChar(@Result[1]);
  P := PByteArray(AMem);
 
  for j := 0 to MemByteLen - 1 do
    begin
    FillAByteToBuf(P^[j], b);
    if Sep then
      begin
      b[8] := ' ';
      Inc(b, 9);
      end
    else
      Inc(b, 8);
    end;
end;
 
procedure MemorySwap(AMem, BMem: Pointer; MemByteLen: integer);
var
  a, b: PCnLongWord32Array;
  BA, BB: PByteArray;
  TC: cardinal;
  TB: byte;
begin
  if (AMem = nil) or (BMem = nil) or (MemByteLen <= 0) then
    Exit;
 
  a := PCnLongWord32Array(AMem);
  b := PCnLongWord32Array(BMem);
 
  if a = b then
    Exit;
 
  while (MemByteLen and (not 3)) <> 0 do
    begin
    TC    := a^[0];
    a^[0] := b^[0];
    b^[0] := TC;
 
    a := PCnLongWord32Array(TCnNativeInt(a) + SizeOf(cardinal));
    b := PCnLongWord32Array(TCnNativeInt(b) + SizeOf(cardinal));
 
    Dec(MemByteLen, SizeOf(cardinal));
    end;
 
  if MemByteLen > 0 then
    begin
    BA := PByteArray(a);
    BB := PByteArray(b);
 
    while MemByteLen <> 0 do
      begin
      TB     := BA^[0];
      BA^[0] := BB^[0];
      BB^[0] := TB;
 
      BA := PByteArray(TCnNativeInt(BA) + SizeOf(byte));
      BB := PByteArray(TCnNativeInt(BB) + SizeOf(byte));
 
      Dec(MemByteLen);
      end;
    end;
end;
 
function MemoryCompare(AMem, BMem: Pointer; MemByteLen: integer): integer;
var
  a, b: PCnLongWord32Array;
  BA, BB: PByteArray;
begin
  Result := 0;
  if ((AMem = nil) and (BMem = nil)) or (AMem = BMem) then // 同一块
    Exit;
 
  if MemByteLen <= 0 then
    Exit;
 
  if AMem = nil then
    begin
    Result := -1;
    Exit;
    end;
  if BMem = nil then
    begin
    Result := 1;
    Exit;
    end;
 
  a := PCnLongWord32Array(AMem);
  b := PCnLongWord32Array(BMem);
 
  while (MemByteLen and (not 3)) <> 0 do
    begin
    if a^[0] > b^[0] then
      begin
      Result := 1;
      Exit;
      end
    else if a^[0] < b^[0] then
        begin
        Result := -1;
        Exit;
        end;
 
    a := PCnLongWord32Array(TCnNativeInt(a) + SizeOf(cardinal));
    b := PCnLongWord32Array(TCnNativeInt(b) + SizeOf(cardinal));
 
    Dec(MemByteLen, SizeOf(cardinal));
    end;
 
  if MemByteLen > 0 then
    begin
    BA := PByteArray(a);
    BB := PByteArray(b);
 
    while MemByteLen <> 0 do
      begin
      if BA^[0] > BB^[0] then
        begin
        Result := 1;
        Exit;
        end
      else if BA^[0] < BB^[0] then
          begin
          Result := -1;
          Exit;
          end;
 
      BA := PByteArray(TCnNativeInt(BA) + SizeOf(byte));
      BB := PByteArray(TCnNativeInt(BB) + SizeOf(byte));
 
      Dec(MemByteLen);
      end;
    end;
end;
 
function UInt8ToBinStr(V: byte): string;
const
  M = $80;
var
  i: integer;
begin
  setlength(Result, 8 * SizeOf(V));
  for i := 1 to 8 * SizeOf(V) do
    begin
    if (V and M) <> 0 then
      Result[i] := '1'
    else
      Result[i] := '0';
    V := V shl 1;
    end;
end;
 
function UInt16ToBinStr(V: word): string;
const
  M = $8000;
var
  i: integer;
begin
  setlength(Result, 8 * SizeOf(V));
  for i := 1 to 8 * SizeOf(V) do
    begin
    if (V and M) <> 0 then
      Result[i] := '1'
    else
      Result[i] := '0';
    V := V shl 1;
    end;
end;
 
function UInt32ToBinStr(V: cardinal): string;
const
  M = $80000000;
var
  i: integer;
begin
  setlength(Result, 8 * SizeOf(V));
  for i := 1 to 8 * SizeOf(V) do
    begin
    if (V and M) <> 0 then
      Result[i] := '1'
    else
      Result[i] := '0';
    V := V shl 1;
    end;
end;
 
function UInt32ToStr(V: cardinal): string;
begin
  Result := format('%u', [V]);
end;
 
function UInt64ToBinStr(V: TUInt64): string;
const
  M = $8000000000000000;
var
  i: integer;
begin
  setlength(Result, 8 * SizeOf(V));
 
  for i := 1 to 8 * SizeOf(V) do
    begin
    if (V and M) <> 0 then
      Result[i] := '1'
    else
      Result[i] := '0';
    V := V shl 1;
    end;
end;
 
const
HiDigits: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
 
const
LoDigits: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
 
const
AnsiHiDigits: array[0..15] of ansichar = ('0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
 
const
AnsiLoDigits: array[0..15] of ansichar = ('0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
 
function HexToInt(Hex: PChar; CharLen: integer): integer;
var
  i, Res: integer;
  c: char;
begin
  Res := 0;
  for i := 0 to CharLen - 1 do
    begin
    c := Hex[i];
    if (c >= '0') and (c <= '9') then
      Res := Res * 16 + Ord(c) - Ord('0')
    else if (c >= 'A') and (c <= 'F') then
        Res := Res * 16 + Ord(c) - Ord('A') + 10
      else if (c >= 'a') and (c <= 'f') then
          Res := Res * 16 + Ord(c) - Ord('a') + 10
        else
          raise Exception.Createfmt('Error: not a Hex PChar: %c', [c]);
    end;
  Result := Res;
end;
 
function HexToInt(const Hex: string): integer;
begin
  Result := HexToInt(PChar(Hex), Length(Hex));
end;
 
{$WARNINGS OFF}
 
function IsHexString(const Hex: string): boolean;
var
  i, L: integer;
begin
  Result := False;
  L      := Length(Hex);
  if (L <= 0) or ((L and 1) <> 0) then // 空或非偶长度都不是
    Exit;
 
  for i := 1 to L do
    begin
    // 注意此处 Unicode 下虽然有 Warning,但并不是将 Hex[I] 这个 WideChar 直接截断至 AnsiChar
    // 后再进行判断(那样会导致“晦晦”这种 $66$66$66$66 的字符串出现误判),而是
    // 直接通过 WideChar 的值(在 ax 中因而是双字节的)加减来判断,不会出现误判
    if not (Hex[i] in ['0'..'9', 'A'..'F', 'a'..'f']) then
      Exit;
    end;
  Result := True;
end;
 
{$WARNINGS ON}
 
function DataToHex(InData: Pointer; ByteLength: integer;
UseUpperCase: boolean = True): string;
var
  i: integer;
  b: byte;
begin
  Result := '';
  if ByteLength <= 0 then
    Exit;
 
  setlength(Result, ByteLength * 2);
  if UseUpperCase then
    begin
    for i := 0 to ByteLength - 1 do
      begin
      b := pbyte(TCnNativeInt(InData) + i * SizeOf(byte))^;
      Result[i * 2 + 1] := HiDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := HiDigits[b and $0F];
      end;
    end
  else
    begin
    for i := 0 to ByteLength - 1 do
      begin
      b := pbyte(TCnNativeInt(InData) + i * SizeOf(byte))^;
      Result[i * 2 + 1] := LoDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := LoDigits[b and $0F];
      end;
    end;
end;
 
function HexToData(const Hex: string; OutData: Pointer): integer;
var
  i, L: integer;
  H: PChar;
begin
  L := Length(Hex);
  if (L mod 2) <> 0 then
    raise Exception.Createfmt('Error Length %d: not a Hex String', [L]);
 
  if OutData = nil then
    begin
    Result := L div 2;
    Exit;
    end;
 
  Result := 0;
  H      := PChar(Hex);
  for i := 1 to L div 2 do
    begin
    pbyte(TCnNativeInt(OutData) + i - 1)^ := byte(HexToInt(@H[(i - 1) * 2], 2));
    Inc(Result);
    end;
end;
 
function StringToHex(const Data: string; UseUpperCase: boolean): string;
var
  i, L: integer;
  b: byte;
  Buffer: PChar;
begin
  Result := '';
  L      := Length(Data);
  if L = 0 then
    Exit;
 
  setlength(Result, L * 2);
  Buffer := @Data[1];
 
  if UseUpperCase then
    begin
    for i := 0 to L - 1 do
      begin
      b := pbyte(TCnNativeInt(Buffer) + i * SizeOf(char))^;
      Result[i * 2 + 1] := HiDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := HiDigits[b and $0F];
      end;
    end
  else
    begin
    for i := 0 to L - 1 do
      begin
      b := pbyte(TCnNativeInt(Buffer) + i * SizeOf(char))^;
      Result[i * 2 + 1] := LoDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := LoDigits[b and $0F];
      end;
    end;
end;
 
function HexToString(const Hex: string): string;
var
  i, L: integer;
  H: PChar;
begin
  L := Length(Hex);
  if (L mod 2) <> 0 then
    raise Exception.Createfmt('Error Length %d: not a Hex String', [L]);
 
  setlength(Result, L div 2);
  H := PChar(Hex);
  for i := 1 to L div 2 do
    Result[i] := Chr(HexToInt(@H[(i - 1) * 2], 2));
end;
 
function HexToAnsiStr(const Hex: ansistring): ansistring;
var
  i, L: integer;
  S: string;
begin
  L := Length(Hex);
  if (L mod 2) <> 0 then
    raise Exception.Createfmt('Error Length %d: not a Hex AnsiString', [L]);
 
  setlength(Result, L div 2);
  for i := 1 to L div 2 do
    begin
    S := string(Copy(Hex, i * 2 - 1, 2));
    Result[i] := ansichar(Chr(HexToInt(S)));
    end;
end;
 
function AnsiStrToHex(const Data: ansistring; UseUpperCase: boolean): ansistring;
var
  i, L: integer;
  b: byte;
  Buffer: pansichar;
begin
  Result := '';
  L      := Length(Data);
  if L = 0 then
    Exit;
 
  setlength(Result, L * 2);
  Buffer := @Data[1];
 
  if UseUpperCase then
    begin
    for i := 0 to L - 1 do
      begin
      b := pbyte(TCnNativeInt(Buffer) + i)^;
      Result[i * 2 + 1] := AnsiHiDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := AnsiHiDigits[b and $0F];
      end;
    end
  else
    begin
    for i := 0 to L - 1 do
      begin
      b := pbyte(TCnNativeInt(Buffer) + i)^;
      Result[i * 2 + 1] := AnsiLoDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := AnsiLoDigits[b and $0F];
      end;
    end;
end;
 
function BytesToHex(Data: TBytes; UseUpperCase: boolean): string;
var
  i, L: integer;
  b: byte;
  Buffer: pansichar;
begin
  Result := '';
  L      := Length(Data);
  if L = 0 then
    Exit;
 
  setlength(Result, L * 2);
  Buffer := @Data[0];
 
  if UseUpperCase then
    begin
    for i := 0 to L - 1 do
      begin
      b := pbyte(TCnNativeInt(Buffer) + i)^;
      Result[i * 2 + 1] := HiDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := HiDigits[b and $0F];
      end;
    end
  else
    begin
    for i := 0 to L - 1 do
      begin
      b := pbyte(TCnNativeInt(Buffer) + i)^;
      Result[i * 2 + 1] := LoDigits[(b shr 4) and $0F];
      Result[i * 2 + 2] := LoDigits[b and $0F];
      end;
    end;
end;
 
function HexToBytes(const Hex: string): TBytes;
var
  i, L: integer;
  H: PChar;
begin
  L := Length(Hex);
  if (L mod 2) <> 0 then
    raise Exception.Createfmt('Error Length %d: not a Hex String', [L]);
 
  setlength(Result, L div 2);
  H := PChar(Hex);
 
  for i := 1 to L div 2 do
    Result[i - 1] := byte(HexToInt(@H[(i - 1) * 2], 2));
end;
 
function StreamToHex(Stream: TStream; UseUpperCase: boolean): string;
var
  b: byte;
  i: integer;
begin
  Result := '';
  if Stream.size > 0 then
    begin
    Stream.Position := 0;
    setlength(Result, Stream.size * 2);
    i := 1;
    if UseUpperCase then
      begin
      while Stream.Read(b, 1) = 1 do
        begin
        Result[i] := HiDigits[(b shr 4) and $0F];
        Inc(i);
        Result[i] := HiDigits[b and $0F];
        Inc(i);
        end;
      end
    else
      begin
      while Stream.Read(b, 1) = 1 do
        begin
        Result[i] := LoDigits[(b shr 4) and $0F];
        Inc(i);
        Result[i] := LoDigits[b and $0F];
        Inc(i);
        end;
      end;
    end;
end;
 
function HexToStream(const Hex: string; Stream: TStream): integer;
var
  i, L: integer;
  H: PChar;
  b: byte;
begin
  Result := 0;
  L      := Length(Hex);
  if (L mod 2) <> 0 then
    raise Exception.Createfmt('Error Length %d: not a Hex String', [L]);
 
  H := PChar(Hex);
  for i := 1 to L div 2 do
    begin
    b := byte(HexToInt(@H[(i - 1) * 2], 2));
    Inc(Result, Stream.Write(b, 1));
    end;
end;
 
procedure ReverseBytes(Data: TBytes);
var
  i, L, M: integer;
  T: byte;
begin
  if (Data = nil) or (Length(Data) <= 1) then
    Exit;
  L := Length(Data);
  M := L div 2;
  for i := 0 to M - 1 do
    begin
    // 交换 I 和 L - I - 1
    T := Data[i];
    Data[i] := Data[L - i - 1];
    Data[L - i - 1] := T;
    end;
end;
 
function StreamToBytes(Stream: TStream): TBytes;
begin
  Result := nil;
  if (Stream <> nil) and (Stream.size > 0) then
    begin
    setlength(Result, Stream.size);
    Stream.Position := 0;
    Stream.Read(Result[0], Stream.size);
    end;
end;
 
function BytesToStream(Data: TBytes; OutStream: TStream): integer;
begin
  Result := 0;
  if (Data <> nil) and (Length(Data) > 0) and (OutStream <> nil) then
    begin
    OutStream.size := 0;
    Result := OutStream.Write(Data[0], Length(Data));
    end;
end;
 
function AnsiToBytes(const str: ansistring): TBytes;
begin
  setlength(Result, Length(str));
  if Length(str) > 0 then
    Move(str[1], Result[0], Length(str));
end;
 
function BytesToAnsi(const Data: TBytes): ansistring;
begin
  setlength(Result, Length(Data));
  if Length(Data) > 0 then
    Move(Data[0], Result[1], Length(Data));
end;
 
function BytesToString(const Data: TBytes): string;
var
  i: integer;
begin
  setlength(Result, Length(Data));
  for i := 1 to Length(Data) do
    Result[i] := Chr(Data[i - 1]);
end;
 
function MemoryToString(Mem: Pointer; MemByteLen: integer): string;
var
  P: PByteArray;
  i: integer;
begin
  if (Mem = nil) or (MemByteLen <= 0) then
    begin
    Result := '';
    Exit;
    end;
 
  P := PByteArray(Mem);
  setlength(Result, MemByteLen);
  for i := 1 to MemByteLen do
    Result[i] := Chr(P^[i - 1]);
end;
 
function ConcatBytes(a, b: TBytes): TBytes;
begin
  // 哪怕是 XE7 后也不能直接相加,因为 A 或 B 为空时会返回另一字节数组而不是新数组
  if (a = nil) or (Length(a) = 0) then
    begin
    setlength(Result, Length(b));
    if Length(b) > 0 then
      Move(b[0], Result[0], Length(b));
    end
  else if (b = nil) or (Length(b) = 0) then
      begin
      setlength(Result, Length(a));
      if Length(a) > 0 then
        Move(a[0], Result[0], Length(a));
      end
    else
      begin
      setlength(Result, Length(a) + Length(b));
      Move(a[0], Result[0], Length(a));
      Move(b[0], Result[Length(a)], Length(b));
      end;
end;
 
function NewBytesFromMemory(Data: Pointer; DataByteLen: integer): TBytes;
begin
  if (Data = nil) or (DataByteLen <= 0) then
    Result := nil
  else
    begin
    setlength(Result, DataByteLen);
    Move(Data^, Result[0], DataByteLen);
    end;
end;
 
function CompareBytes(a, b: TBytes): boolean;
var
  L: integer;
begin
  Result := False;
 
  L := Length(a);
  if Length(b) <> L then // 长度不等则退出
    Exit;
 
  if L = 0 then          // 长度相等
    Result := True       // 如都是 0 视作相等
  else
    Result := CompareMem(@a[0], @b[0], L);
end;
 
procedure MoveMost(const Source; var Dest; ByteLen, MostLen: integer);
begin
  if MostLen <= 0 then
    Exit;
 
  if ByteLen > MostLen then
    ByteLen := MostLen
  else if ByteLen < MostLen then
      // TODO: 可优化为只填充不满的部分但后面有空再整
      FillChar(Dest, MostLen, 0);
 
  Move(Source, Dest, ByteLen);
end;
 
procedure ConstTimeConditionalSwap8(CanSwap: boolean; var a, b: byte);
var
  T, V: byte;
begin
  T := ConstTimeExpandBoolean8(CanSwap);
  V := (a xor b) and T;
  a := a xor V;
  b := b xor V;
end;
 
procedure ConstTimeConditionalSwap16(CanSwap: boolean; var a, b: word);
var
  T, V: word;
begin
  T := ConstTimeExpandBoolean16(CanSwap);
  V := (a xor b) and T;
  a := a xor V;
  b := b xor V;
end;
 
procedure ConstTimeConditionalSwap32(CanSwap: boolean; var a, b: cardinal);
var
  T, V: cardinal;
begin
  T := ConstTimeExpandBoolean32(CanSwap);
  V := (a xor b) and T;
  a := a xor V;
  b := b xor V;
end;
 
procedure ConstTimeConditionalSwap64(CanSwap: boolean; var a, b: TUInt64);
var
  T, V: TUInt64;
begin
  T := ConstTimeExpandBoolean64(CanSwap);
  V := (a xor b) and T;
  a := a xor V;
  b := b xor V;
end;
 
function ConstTimeEqual8(a, b: byte): boolean;
var
  r: byte;
begin
  r      := not (a xor b);     // 异或后求反
  r      := r and (r shr 4);   // 以下一半一半地与
  r      := r and (r shr 2);   // 如果有一位出现 0
  r      := r and (r shr 1);   // 最后结果就是 0
  Result := boolean(r);   // 只有全 1 才是 1
end;
 
function ConstTimeEqual16(a, b: word): boolean;
begin
  Result := ConstTimeEqual8(byte(a shr 8), byte(b shr 8)) and
    ConstTimeEqual8(byte(a and $FF), byte(b and $FF));
end;
 
function ConstTimeEqual32(a, b: cardinal): boolean;
begin
  Result := ConstTimeEqual16(word(a shr 16), word(b shr 16)) and
    ConstTimeEqual16(word(a and $FFFF), word(b and $FFFF));
end;
 
function ConstTimeEqual64(a, b: TUInt64): boolean;
begin
  Result := ConstTimeEqual32(cardinal(a shr 32), cardinal(b shr 32)) and
    ConstTimeEqual32(cardinal(a and $FFFFFFFF), cardinal(b and $FFFFFFFF));
end;
 
function ConstTimeBytesEqual(a, b: TBytes): boolean;
var
  i: integer;
begin
  Result := False;
  if Length(a) <> Length(b) then
    Exit;
 
  Result := True;
  for i := 0 to Length(a) - 1 do
    // 每个字节都比较,而不是碰到不同就退出
    Result := Result and (ConstTimeEqual8(a[i], b[i]));
end;
 
function ConstTimeExpandBoolean8(V: boolean): byte;
begin
  Result := byte(V);
  Result := not Result;
  // 如果 V 是 True,非 0,则此步 R 非纯 $FF,R 里头有 0
  Result := Result and (Result shr 4);   // 以下一半一半地与
  Result := Result and (Result shr 2);   // 如果有一位出现 0
  Result := Result and (Result shr 1);   // 最后结果就是 00000000,否则 00000001
  Result := Result or (Result shl 1);
  // True 得到 00000000,False 得到 00000001,再往高位两倍两倍地扩
  Result := Result or (Result shl 2);
  Result := Result or (Result shl 4);    // 最终全 0 或 全 1
  Result := not Result;                  // 反成全 1 或全 0
end;
 
function ConstTimeExpandBoolean16(V: boolean): word;
var
  r: byte;
begin
  r      := ConstTimeExpandBoolean8(V);
  Result := r;
  Result := (Result shl 8) or r;         // 单字节全 1 或全 0 扩成双字节
end;
 
function ConstTimeExpandBoolean32(V: boolean): cardinal;
var
  r: word;
begin
  r      := ConstTimeExpandBoolean16(V);
  Result := r;
  Result := (Result shl 16) or r;        // 双字节全 1 或全 0 扩成四字节
end;
 
function ConstTimeExpandBoolean64(V: boolean): TUInt64;
var
  r: cardinal;
begin
  r      := ConstTimeExpandBoolean32(V);
  Result := r;
  Result := (Result shl 32) or r;        // 四字节全 1 或全 0 扩成八字节
end;
 
function ConstTimeConditionalSelect8(Condition: boolean; a, b: byte): byte;
begin
  ConstTimeConditionalSwap8(Condition, a, b);
  Result := b;
end;
 
function ConstTimeConditionalSelect16(Condition: boolean; a, b: word): word;
begin
  ConstTimeConditionalSwap16(Condition, a, b);
  Result := b;
end;
 
function ConstTimeConditionalSelect32(Condition: boolean; a, b: cardinal): cardinal;
begin
  ConstTimeConditionalSwap32(Condition, a, b);
  Result := b;
end;
 
function ConstTimeConditionalSelect64(Condition: boolean; a, b: TUInt64): TUInt64;
begin
  ConstTimeConditionalSwap64(Condition, a, b);
  Result := b;
end;
 
{$IFDEF MSWINDOWS}
 
{$IFDEF CPUX64}
 
// 64 位汇编用 IDIV 和 IDIV 指令实现,其中 A 在 RCX 里,B 在 EDX/RDX 里,DivRes 地址在 R8 里,ModRes 地址在 R9 里
procedure Int64DivInt32Mod(A: Int64; B: Integer; var DivRes, ModRes: Integer); assembler;
asm
        PUSH    RCX                           // RCX 是 A
        MOV     RCX, RDX                      // 除数 B 放入 RCX
        POP     RAX                           // 被除数 A 放入 RAX
        XOR     RDX, RDX                      // 被除数高 64 位清零
        IDIV    RCX
        MOV     [R8], EAX                     // 商放入 R8 所指的 DivRes
        MOV     [R9], EDX                     // 余数放入 R9 所指的 ModRes
end;
 
procedure UInt64DivUInt32Mod(A: TUInt64; B: Cardinal; var DivRes, ModRes: Cardinal); assembler;
asm
        PUSH    RCX                           // RCX 是 A
        MOV     RCX, RDX                      // 除数 B 放入 RCX
        POP     RAX                           // 被除数 A 放入 RAX
        XOR     RDX, RDX                      // 被除数高 64 位清零
        DIV     RCX
        MOV     [R8], EAX                     // 商放入 R8 所指的 DivRes
        MOV     [R9], EDX                     // 余数放入 R9 所指的 ModRes
end;
 
// 64 位汇编用 IDIV 和 IDIV 指令实现,ALo 在 RCX,AHi 在 RDX,B 在 R8,DivRes 的地址在 R9,
procedure Int128DivInt64Mod(ALo, AHi: Int64; B: Int64; var DivRes, ModRes: Int64); assembler;
asm
        MOV     RAX, RCX                      // ALo 放入 RAX,AHi 已经在 RDX 了
        MOV     RCX, R8                       // B 放入 RCX
        IDIV    RCX
        MOV     [R9], RAX                     // 商放入 R9 所指的 DivRes
        MOV     RAX, [RBP + $30]              // ModRes 地址放入 RAX
        MOV     [RAX], RDX                    // 余数放入 RAX 所指的 ModRes
end;
 
procedure UInt128DivUInt64Mod(ALo, AHi: UInt64; B: UInt64; var DivRes, ModRes: UInt64); assembler;
asm
        MOV     RAX, RCX                      // ALo 放入 RAX,AHi 已经在 RDX 了
        MOV     RCX, R8                       // B 放入 RCX
        DIV     RCX
        MOV     [R9], RAX                     // 商放入 R9 所指的 DivRes
        MOV     RAX, [RBP + $30]              // ModRes 地址放入 RAX
        MOV     [RAX], RDX                    // 余数放入 RAX 所指的 ModRes
end;
 
{$ELSE}
 
// 32 位汇编用 IDIV 和 IDIV 指令实现,其中 A 在堆栈上,B 在 EAX,DivRes 地址在 EDX,ModRes 地址在 ECX
procedure Int64DivInt32Mod(a: int64; b: integer; var DivRes, ModRes: integer); {$asmmode intel} assembler;
asm
         PUSH    ECX                           // ECX 是 ModRes 地址,先保存
         MOV     ECX, B                        // B 在 EAX 中,搬移到 ECX 中
         PUSH    EDX                           // DivRes 的地址在 EDX 中,也保存
         MOV     EAX, [EBP + $8]               // A Lo
         MOV     EDX, [EBP + $C]               // A Hi
         IDIV    ECX
         POP     ECX                           // 弹出 ECX,拿到 DivRes 地址
         MOV     [ECX], EAX
         POP     ECX                           // 弹出 ECX,拿到 ModRes 地址
         MOV     [ECX], EDX
end;
 
procedure UInt64DivUInt32Mod(a: TUInt64; b: cardinal; var DivRes, ModRes: cardinal);
{$asmmode intel} assembler;
asm
         PUSH    ECX                           // ECX 是 ModRes 地址,先保存
         MOV     ECX, B                        // B 在 EAX 中,搬移到 ECX 中
         PUSH    EDX                           // DivRes 的地址在 EDX 中,也保存
         MOV     EAX, [EBP + $8]               // A Lo
         MOV     EDX, [EBP + $C]               // A Hi
         DIV     ECX
         POP     ECX                           // 弹出 ECX,拿到 DivRes 地址
         MOV     [ECX], EAX
         POP     ECX                           // 弹出 ECX,拿到 ModRes 地址
         MOV     [ECX], EDX
end;
 
// 32 位下的实现
procedure Int128DivInt64Mod(ALo, AHi: int64; b: int64; var DivRes, ModRes: int64);
var
  c: integer;
begin
  if b = 0 then
    raise EDivByZero.Create(SDivByZero);
 
  if (AHi = 0) or (AHi = $FFFFFFFFFFFFFFFF) then // 高 64 位为 0 的正值或负值
    begin
    DivRes := ALo div b;
    ModRes := ALo mod b;
    end
  else
    begin
    if b < 0 then // 除数是负数
      begin
      Int128DivInt64Mod(ALo, AHi, -b, DivRes, ModRes);
      DivRes := -DivRes;
      Exit;
      end;
 
    if AHi < 0 then // 被除数是负数
      begin
      // AHi, ALo 求反加 1,以得到正值
      AHi := not AHi;
      ALo := not ALo;
{$IFDEF SUPPORT_UINT64}
      UInt64Add(UInt64(ALo), UInt64(ALo), 1, C);
{$ELSE}
      UInt64Add(ALo, ALo, 1, c);
{$ENDIF}
      if c > 0 then
        AHi := AHi + c;
 
      // 被除数转正了
      Int128DivInt64Mod(ALo, AHi, b, DivRes, ModRes);
 
      // 结果再调整
      if ModRes = 0 then
        DivRes := -DivRes
      else
        begin
        DivRes := -DivRes - 1;
        ModRes := b - ModRes;
        end;
      Exit;
      end;
 
    // 全正后,按无符号来除
{$IFDEF SUPPORT_UINT64}
    UInt128DivUInt64Mod(TUInt64(ALo), TUInt64(AHi), TUInt64(B), TUInt64(DivRes), TUInt64(ModRes));
{$ELSE}
    UInt128DivUInt64Mod(ALo, AHi, b, DivRes, ModRes);
{$ENDIF}
    end;
end;
 
procedure UInt128DivUInt64Mod(ALo, AHi: TUInt64; b: TUInt64;
var DivRes, ModRes: TUInt64);
var
  i, Cnt: integer;
  Q, r: TUInt64;
begin
  if b = 0 then
    raise EDivByZero.Create(SDivByZero);
 
  if AHi = 0 then
    begin
    DivRes := UInt64Div(ALo, b);
    ModRes := UInt64Mod(ALo, b);
    end
  else
    begin
    // 有高位有低位咋办?先判断是否会溢出,如果 AHi >= B,则表示商要超 64 位,溢出
    if UInt64Compare(AHi, b) >= 0 then
      raise Exception.Create(SIntOverflow);
 
    Q   := 0;
    r   := 0;
    Cnt := GetUInt64LowBits(AHi) + 64;
    for i := Cnt downto 0 do
      begin
      r := r shl 1;
      if IsUInt128BitSet(ALo, AHi, i) then  // 被除数的第 I 位是否是 0
        r := r or 1
      else
        r := r and TUInt64(not 1);
 
      if UInt64Compare(r, b) >= 0 then
        begin
        r := r - b;
        Q := Q or (TUInt64(1) shl i);
        end;
      end;
    DivRes := Q;
    ModRes := r;
    end;
end;
 
{$ENDIF}
 
{$ENDIF}
 
{$IFDEF SUPPORT_UINT64}
 
// 只要支持 64 位无符号整数,无论 32/64 位 Intel 还是 ARM,无论 Delphi 还是 FPC,无论什么操作系统都能如此
 
function UInt64Mod(A, B: TUInt64): TUInt64;
begin
  Result := A mod B;
end;
 
function UInt64Div(A, B: TUInt64): TUInt64;
begin
  Result := A div B;
end;
 
{$ELSE}
{
  不支持 UInt64 的低版本 Delphi 下用 Int64 求 A mod/div B
 
  调用的入栈顺序是 A 的高位,A 的低位,B 的高位,B 的低位。挨个 push 完毕并进入函数后,
  ESP 是返回地址,ESP+4 是 B 的低位,ESP + 8 是 B 的高位,ESP + C 是 A 的低位,ESP + 10 是 A 的高位
  进入后 push esp 让 ESP 减了 4,然后 mov ebp esp,之后用 EBP 来寻址,全要多加 4
 
  而 System.@_llumod 要求在刚进入时,EAX <- A 的低位,EDX <- A 的高位,(System 源码注释中 EAX/EDX 写反了)
  [ESP + 8](也就是 EBP + C)<- B 的高位,[ESP + 4] (也就是 EBP + 8)<- B 的低位
 
  所以 CALL 前加了四句搬移代码。UInt64 Div 的也类似
}
function UInt64Mod(a, b: TUInt64): TUInt64;
begin
  {$asmmode intel}
asm
         // PUSH ESP 让 ESP 减了 4,要补上
         MOV     EAX, [EBP + $10]              // A Lo
         MOV     EDX, [EBP + $14]              // A Hi
         PUSH    DWORD PTR[EBP + $C]           // B Hi
         PUSH    DWORD PTR[EBP + $8]           // B Lo
         CALL    System.@_llumod;
end;
end;
function UInt64Div(a, b: TUInt64): TUInt64;
asm
         // PUSH ESP 让 ESP 减了 4,要补上
         MOV     EAX, [EBP + $10]              // A Lo
         MOV     EDX, [EBP + $14]              // A Hi
         PUSH    DWORD PTR[EBP + $C]           // B Hi
         PUSH    DWORD PTR[EBP + $8]           // B Lo
         CALL    System.@_lludiv;
end;
 
{$ENDIF}
 
{$IFDEF SUPPORT_UINT64}
 
// 只要支持 64 位无符号整数,无论 32/64 位 Intel 还是 ARM,无论 Delphi 还是 FPC,无论什么操作系统都能如此
 
function UInt64Mul(A, B: Cardinal): TUInt64;
begin
  Result := TUInt64(A) * B;
end;
 
{$ELSE}// 只有低版本 Delphi 会进这里,Win32 x86
 
{
  无符号 32 位整数相乘,如果结果直接使用 Int64 会溢出,模拟 64 位无符号运算
 
  调用寄存器约定是 A -> EAX,B -> EDX,不使用堆栈
  而 System.@_llmul 要求在刚进入时,EAX <- A 的低位,EDX <- A 的高位 0,
  [ESP + 8](也就是 EBP + C)<- B 的高位 0,[ESP + 4] (也就是 EBP + 8)<- B 的低位
}
function UInt64Mul(a, b: cardinal): TUInt64;
asm
         PUSH    0               // PUSH B 高位 0
         PUSH    EDX             // PUSH B 低位
         // EAX A 低位,已经是了
         XOR     EDX, EDX        // EDX A 高位 0
         CALL    System.@_llmul; // 返回 EAX 低 32 位、EDX 高 32 位
end;
 
{$ENDIF}
 
// 两个无符号 64 位整数相加,处理溢出的情况,结果放 ResLo 与 ResHi 中
procedure UInt64AddUInt64(a, b: TUInt64; var ResLo, ResHi: TUInt64);
var
  x, y, Z, T, R0L, R0H, R1L, R1H: cardinal;
  R0, R1, R01, R12: TUInt64;
begin
  // 基本思想:2^32 是系数 M,拆成 (xM+y) + (zM+t) = (x+z) M + (y+t)
  // y+t 是 R0 占 0、1,x+z 是 R1 占 1、2,把 R0, R1 再拆开相加成 R01, R12
  if IsUInt64AddOverflow(a, b) then
    begin
    x := Int64Rec(a).Hi;
    y := Int64Rec(a).Lo;
    Z := Int64Rec(b).Hi;
    T := Int64Rec(b).Lo;
 
    R0 := TUInt64(y) + TUInt64(T);
    R1 := TUInt64(x) + TUInt64(Z);
 
    R0L := Int64Rec(R0).Lo;
    R0H := Int64Rec(R0).Hi;
    R1L := Int64Rec(R1).Lo;
    R1H := Int64Rec(R1).Hi;
 
    R01 := TUInt64(R0H) + TUInt64(R1L);
    R12 := TUInt64(R1H) + TUInt64(Int64Rec(R01).Hi);
 
    Int64Rec(ResLo).Lo := R0L;
    Int64Rec(ResLo).Hi := Int64Rec(R01).Lo;
    Int64Rec(ResHi).Lo := Int64Rec(R12).Lo;
    Int64Rec(ResHi).Hi := Int64Rec(R12).Hi;
    end
  else
    begin
    ResLo := a + b;
    ResHi := 0;
    end;
end;
 
{$IFDEF WIN64}  // 注意 Linux 64 下不支持 ASM,只能 WIN64
 
// 64 位下两个无符号 64 位整数相乘,结果放 ResLo 与 ResHi 中,直接用汇编实现,比下面快了一倍以上
procedure UInt64MulUInt64(A, B: UInt64; var ResLo, ResHi: UInt64); assembler;
asm
  PUSH RAX
  MOV RAX, RCX
  MUL RDX         // 得用无符号,不能用有符号的 IMUL
  MOV [R8], RAX
  MOV [R9], RDX
  POP RAX
end;
 
{$ELSE}
 
// 两个无符号 64 位整数相乘,结果放 ResLo 与 ResHi 中
procedure UInt64MulUInt64(a, b: TUInt64; var ResLo, ResHi: TUInt64);
var
  x, y, Z, T: cardinal;
  YT, XT, ZY, ZX: TUInt64;
  P, R1Lo, R1Hi, R2Lo, R2Hi: TUInt64;
begin
  // 基本思想:2^32 是系数 M,拆成 (xM+y)*(zM+t) = xzM^2 + (xt+yz)M + yt
  // 各项系数都是 UInt64,xz 占 2、3、4,xt+yz 占 1、2、3,yt 占 0、1,然后累加
  x := Int64Rec(a).Hi;
  y := Int64Rec(a).Lo;
  Z := Int64Rec(b).Hi;
  T := Int64Rec(b).Lo;
 
  YT := UInt64Mul(y, T);
  XT := UInt64Mul(x, T);
  ZY := UInt64Mul(y, Z);
  ZX := UInt64Mul(x, Z);
 
  Int64Rec(ResLo).Lo := Int64Rec(YT).Lo;
 
  P := Int64Rec(YT).Hi;
  UInt64AddUInt64(P, XT, R1Lo, R1Hi);
  UInt64AddUInt64(ZY, R1Lo, R2Lo, R2Hi);
 
  Int64Rec(ResLo).Hi := Int64Rec(R2Lo).Lo;
 
  P := TUInt64(Int64Rec(R2Lo).Hi) + TUInt64(Int64Rec(ZX).Lo);
 
  Int64Rec(ResHi).Lo := Int64Rec(P).Lo;
  Int64Rec(ResHi).Hi := Int64Rec(R1Hi).Lo + Int64Rec(R2Hi).Lo +
    Int64Rec(ZX).Hi + Int64Rec(P).Hi;
end;
 
{$ENDIF}
 
{$HINTS OFF}
 
function _ValUInt64(const S: string; var Code: integer): TUInt64;
const
  FirstIndex = 1;
var
  i: integer;
  Dig: integer;
  Sign: boolean;
  Empty: boolean;
begin
  i      := FirstIndex;
  Dig    := 0;    // To avoid warning
  Result := 0;
 
  if S = '' then
    begin
    Code := 1;
    Exit;
    end;
  while S[i] = char(' ') do
    Inc(i);
  Sign := False;
  if S[i] = char('-') then
    begin
    Sign := True;
    Inc(i);
    end
  else if S[i] = char('+') then
      Inc(i);
  Empty := True;
 
  if (S[i] = char('$')) or (UpCase(S[i]) = char('X')) or
    ((S[i] = char('0')) and (i < Length(S)) and (UpCase(S[i + 1]) = char('X'))) then
    begin
    if S[i] = char('0') then
      Inc(i);
    Inc(i);
    while True do
      begin
      case char(S[i]) of
        char('0').. char('9'): Dig := Ord(S[i]) - Ord('0');
        char('A').. char('F'): Dig := Ord(S[i]) - (Ord('A') - 10);
        char('a').. char('f'): Dig := Ord(S[i]) - (Ord('a') - 10);
        else
          Break;
        end;
      if Result > (CN_MAX_TUINT64 shr 4) then
        Break;
      if Sign and (Dig <> 0) then
        Break;
      Result := Result shl 4 + TUInt64(Dig);
      Inc(i);
      Empty := False;
      end;
    end
  else
    begin
    while True do
      begin
      case char(S[i]) of
        char('0').. char('9'): Dig := Ord(S[i]) - Ord('0');
        else
          Break;
        end;
 
      if Result > UInt64Div(CN_MAX_TUINT64, 10) then
        Break;
      if Sign and (Dig <> 0) then
        Break;
      Result := Result * 10 + TUInt64(Dig);
      Inc(i);
      Empty := False;
      end;
    end;
 
  if (S[i] <> char(#0)) or Empty then
    Code := i + 1 - FirstIndex
  else
    Code := 0;
end;
 
{$HINTS ON}
 
function UInt64ToHex(N: TUInt64): string;
const
  Digits: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
 
function HC(b: byte): string;
  begin
    Result := string(Digits[(b shr 4) and $0F] + Digits[b and $0F]);
  end;
 
begin
  Result :=
    HC(byte((N and $FF00000000000000) shr 56)) +
    HC(byte((N and $00FF000000000000) shr 48)) +
    HC(byte((N and $0000FF0000000000) shr 40)) +
    HC(byte((N and $000000FF00000000) shr 32)) +
    HC(byte((N and $00000000FF000000) shr 24)) +
    HC(byte((N and $0000000000FF0000) shr 16)) +
    HC(byte((N and $000000000000FF00) shr 8)) + HC(byte((N and $00000000000000FF)));
end;
 
function UInt64ToStr(N: TUInt64): string;
begin
  Result := format('%u', [N]);
end;
 
function StrToUInt64(const S: string): TUInt64;
{$IFNDEF DELPHIXE6_UP}
var
  e: integer;
{$ENDIF}
begin
{$IFDEF DELPHIXE6_UP}
  Result := SysUtils.StrToUInt64(S);  // StrToUInt64 only exists under XE6 or above
{$ELSE}
  Result := _ValUInt64(S, e);
  if e <> 0 then raise EConvertError.CreateResFmt(@SInvalidInteger, [S]);
{$ENDIF}
end;
 
function UInt64Compare(a, b: TUInt64): integer;
{$IFNDEF SUPPORT_UINT64}
var
  HiA, HiB, LoA, LoB: longword;
{$ENDIF}
begin
{$IFDEF SUPPORT_UINT64}
  if A > B then
    Result := 1
  else if A < B then
    Result := -1
  else
    Result := 0;
{$ELSE}
  HiA := (a and $FFFFFFFF00000000) shr 32;
  HiB := (b and $FFFFFFFF00000000) shr 32;
  if HiA > HiB then
    Result := 1
  else if HiA < HiB then
      Result := -1
    else
      begin
      LoA := longword(a and $00000000FFFFFFFF);
      LoB := longword(b and $00000000FFFFFFFF);
      if LoA > LoB then
        Result := 1
      else if LoA < LoB then
          Result := -1
        else
          Result := 0;
      end;
{$ENDIF}
end;
 
function UInt64Sqrt(N: TUInt64): TUInt64;
var
  Rem, Root: TUInt64;
  i: integer;
begin
  Result := 0;
  if N = 0 then
    Exit;
 
  if UInt64Compare(N, 4) < 0 then
    begin
    Result := 1;
    Exit;
    end;
 
  Rem  := 0;
  Root := 0;
 
  for i := 0 to 31 do
    begin
    Root := Root shl 1;
    Inc(Root);
 
    Rem := Rem shl 2;
    Rem := Rem or (N shr 62);
    N   := N shl 2;
 
    if UInt64Compare(Root, Rem) <= 0 then
      begin
      Rem := Rem - Root;
      Inc(Root);
      end
    else
      Dec(Root);
    end;
  Result := Root shr 1;
end;
 
function UInt32IsNegative(N: cardinal): boolean;
begin
  Result := (N and (1 shl 31)) <> 0;
end;
 
function UInt64IsNegative(N: TUInt64): boolean;
begin
{$IFDEF SUPPORT_UINT64}
  Result := (N and (UInt64(1) shl 63)) <> 0;
{$ELSE}
  Result := N < 0;
{$ENDIF}
end;
 
// 给 UInt64 的某一位置 1,位 Index 从 0 开始
procedure UInt64SetBit(var b: TUInt64; Index: integer);
begin
  b := b or (TUInt64(1) shl Index);
end;
 
// 给 UInt64 的某一位置 0,位 Index 从 0 开始
procedure UInt64ClearBit(var b: TUInt64; Index: integer);
begin
  b := b and not (TUInt64(1) shl Index);
end;
 
// 返回 UInt64 的第几位是否是 1,0 开始
function GetUInt64BitSet(b: TUInt64; Index: integer): boolean;
begin
  b      := b and (TUInt64(1) shl Index);
  Result := b <> 0;
end;
 
// 返回 UInt64 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1
function GetUInt64HighBits(b: TUInt64): integer;
begin
  if b = 0 then
    begin
    Result := -1;
    Exit;
    end;
 
  Result := 1;
  if b shr 32 = 0 then
    begin
    Inc(Result, 32);
    b := b shl 32;
    end;
  if b shr 48 = 0 then
    begin
    Inc(Result, 16);
    b := b shl 16;
    end;
  if b shr 56 = 0 then
    begin
    Inc(Result, 8);
    b := b shl 8;
    end;
  if b shr 60 = 0 then
    begin
    Inc(Result, 4);
    b := b shl 4;
    end;
  if b shr 62 = 0 then
    begin
    Inc(Result, 2);
    b := b shl 2;
    end;
  Result := Result - integer(b shr 63); // 得到前导 0 的数量
  Result := 63 - Result;
end;
 
// 返回 Cardinal 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1
function GetUInt32HighBits(b: cardinal): integer;
begin
  if b = 0 then
    begin
    Result := -1;
    Exit;
    end;
 
  Result := 1;
  if b shr 16 = 0 then
    begin
    Inc(Result, 16);
    b := b shl 16;
    end;
  if b shr 24 = 0 then
    begin
    Inc(Result, 8);
    b := b shl 8;
    end;
  if b shr 28 = 0 then
    begin
    Inc(Result, 4);
    b := b shl 4;
    end;
  if b shr 30 = 0 then
    begin
    Inc(Result, 2);
    b := b shl 2;
    end;
  Result := Result - integer(b shr 31); // 得到前导 0 的数量
  Result := 31 - Result;
end;
 
function GetUInt16HighBits(b: word): integer;
begin
  if b = 0 then
    begin
    Result := -1;
    Exit;
    end;
 
  Result := 1;
  if b shr 8 = 0 then
    begin
    Inc(Result, 8);
    b := b shl 8;
    end;
  if b shr 12 = 0 then
    begin
    Inc(Result, 4);
    b := b shl 4;
    end;
  if b shr 14 = 0 then
    begin
    Inc(Result, 2);
    b := b shl 2;
    end;
  Result := Result - integer(b shr 15); // 得到前导 0 的数量
  Result := 15 - Result;
end;
 
function GetUInt8HighBits(b: byte): integer;
begin
  if b = 0 then
    begin
    Result := -1;
    Exit;
    end;
 
  Result := 1;
  if b shr 4 = 0 then
    begin
    Inc(Result, 4);
    b := b shl 4;
    end;
  if b shr 6 = 0 then
    begin
    Inc(Result, 2);
    b := b shl 2;
    end;
  Result := Result - integer(b shr 7); // 得到前导 0 的数量
  Result := 7 - Result;
end;
 
// 返回 Int64 的是 1 的最低二进制位是第几位,最低位是 0,如果没有 1,返回 -1
function GetUInt64LowBits(b: TUInt64): integer;
var
  y: TUInt64;
  N: integer;
begin
  Result := -1;
  if b = 0 then
    Exit;
 
  N := 63;
  y := b shl 32;
  if y <> 0 then
    begin
    Dec(N, 32);
    b := y;
    end;
  y := b shl 16;
  if y <> 0 then
    begin
    Dec(N, 16);
    b := y;
    end;
  y := b shl 8;
  if y <> 0 then
    begin
    Dec(N, 8);
    b := y;
    end;
  y := b shl 4;
  if y <> 0 then
    begin
    Dec(N, 4);
    b := y;
    end;
  y := b shl 2;
  if y <> 0 then
    begin
    Dec(N, 2);
    b := y;
    end;
  b      := b shl 1;
  Result := N - integer(b shr 63);
end;
 
// 返回 Cardinal 的是 1 的最低二进制位是第几位,最低位是 0,如果没有 1,返回 -1
function GetUInt32LowBits(b: cardinal): integer;
var
  y, N: integer;
begin
  Result := -1;
  if b = 0 then
    Exit;
 
  N := 31;
  y := b shl 16;
  if y <> 0 then
    begin
    Dec(N, 16);
    b := y;
    end;
  y := b shl 8;
  if y <> 0 then
    begin
    Dec(N, 8);
    b := y;
    end;
  y := b shl 4;
  if y <> 0 then
    begin
    Dec(N, 4);
    b := y;
    end;
  y := b shl 2;
  if y <> 0 then
    begin
    Dec(N, 2);
    b := y;
    end;
  b      := b shl 1;
  Result := N - integer(b shr 31);
end;
 
// 返回 Word 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1
function GetUInt16LowBits(b: word): integer;
var
  y, N: integer;
begin
  Result := -1;
  if b = 0 then
    Exit;
 
  N := 15;
  y := b shl 8;
  if y <> 0 then
    begin
    Dec(N, 8);
    b := y;
    end;
  y := b shl 4;
  if y <> 0 then
    begin
    Dec(N, 4);
    b := y;
    end;
  y := b shl 2;
  if y <> 0 then
    begin
    Dec(N, 2);
    b := y;
    end;
  b      := b shl 1;
  Result := N - integer(b shr 15);
end;
 
// 返回 Byte 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1
function GetUInt8LowBits(b: byte): integer;
var
  N: integer;
begin
  Result := -1;
  if b = 0 then
    Exit;
 
  N := 7;
  if b shr 4 = 0 then
    begin
    Dec(N, 4);
    b := b shl 4;
    end;
  if b shr 6 = 0 then
    begin
    Dec(N, 2);
    b := b shl 2;
    end;
  b      := b shl 1;
  Result := N - integer(b shr 7);
end;
 
// 封装的 Int64 Mod,碰到负值时取反求模再模减
function Int64Mod(M, N: int64): int64;
begin
  if M > 0 then
    Result := M mod N
  else
    Result := N - ((-M) mod N);
end;
 
// 判断一 32 位无符号整数是否 2 的整数次幂
function IsUInt32PowerOf2(N: cardinal): boolean;
begin
  Result := (N and (N - 1)) = 0;
end;
 
// 判断一 64 位无符号整数是否 2 的整数次幂
function IsUInt64PowerOf2(N: TUInt64): boolean;
begin
  Result := (N and (N - 1)) = 0;
end;
 
// 得到一比指定 32 位无符号整数数大或等的 2 的整数次幂,如溢出则返回 0
function GetUInt32PowerOf2GreaterEqual(N: cardinal): cardinal;
begin
  Result := N - 1;
  Result := Result or (Result shr 1);
  Result := Result or (Result shr 2);
  Result := Result or (Result shr 4);
  Result := Result or (Result shr 8);
  Result := Result or (Result shr 16);
  Inc(Result);
end;
 
// 得到一比指定 64 位无符号整数数大的 2 的整数次幂,如溢出则返回 0
function GetUInt64PowerOf2GreaterEqual(N: TUInt64): TUInt64;
begin
  Result := N - 1;
  Result := Result or (Result shr 1);
  Result := Result or (Result shr 2);
  Result := Result or (Result shr 4);
  Result := Result or (Result shr 8);
  Result := Result or (Result shr 16);
  Result := Result or (Result shr 32);
  Inc(Result);
end;
 
// 判断两个 32 位有符号数相加是否溢出 32 位有符号上限
function IsInt32AddOverflow(a, b: integer): boolean;
var
  c: integer;
begin
  c      := a + b;
  Result := ((a > 0) and (b > 0) and (c < 0)) or
    // 同符号且结果换号了说明出现了溢出
    ((a < 0) and (b < 0) and (c > 0));
end;
 
// 判断两个 32 位无符号数相加是否溢出 32 位无符号上限
function IsUInt32AddOverflow(a, b: cardinal): boolean;
begin
  Result := (a + b) < a;
  // 无符号相加,结果只要小于任一个数就说明溢出了
end;
 
// 判断两个 64 位有符号数相加是否溢出 64 位有符号上限
function IsInt64AddOverflow(a, b: int64): boolean;
var
  c: int64;
begin
  c      := a + b;
  Result := ((a > 0) and (b > 0) and (c < 0)) or
    // 同符号且结果换号了说明出现了溢出
    ((a < 0) and (b < 0) and (c > 0));
end;
 
// 判断两个 64 位无符号数相加是否溢出 64 位无符号上限
function IsUInt64AddOverflow(a, b: TUInt64): boolean;
begin
  Result := UInt64Compare(a + b, a) < 0;
  // 无符号相加,结果只要小于任一个数就说明溢出了
end;
 
// 两个 64 位无符号数相加,A + B => R,如果有溢出,则溢出的 1 搁进位标记里,否则清零
procedure UInt64Add(var r: TUInt64; a, b: TUInt64; out Carry: integer);
begin
  r := a + b;
  if UInt64Compare(r, a) < 0 then
    // 无符号相加,结果只要小于任一个数就说明溢出了
    Carry := 1
  else
    Carry := 0;
end;
 
// 两个 64 位无符号数相减,A - B => R,如果不够减有借位,则借的 1 搁借位标记里,否则清零
procedure UInt64Sub(var r: TUInt64; a, b: TUInt64; out Carry: integer);
begin
  r := a - b;
  if UInt64Compare(r, a) > 0 then
    // 无符号相减,结果只要大于被减数就说明借位了
    Carry := 1
  else
    Carry := 0;
end;
 
// 判断两个 32 位有符号数相乘是否溢出 32 位有符号上限
function IsInt32MulOverflow(a, b: integer): boolean;
var
  T: integer;
begin
  T      := a * b;
  Result := (b <> 0) and ((T div b) <> a);
end;
 
// 判断两个 32 位无符号数相乘是否溢出 32 位无符号上限
function IsUInt32MulOverflow(a, b: cardinal): boolean;
var
  T: TUInt64;
begin
  T      := TUInt64(a) * TUInt64(b);
  Result := (T = cardinal(T));
end;
 
// 判断两个 32 位无符号数相乘是否溢出 64 位有符号数,如未溢出也即返回 False 时,R 中直接返回结果
function IsUInt32MulOverflowInt64(a, b: cardinal; out r: TUInt64): boolean;
var
  T: int64;
begin
  T      := int64(a) * int64(b);
  Result := T < 0; // 如果出现 Int64 负值则说明溢出
  if not Result then
    r := TUInt64(T);
end;
 
// 判断两个 64 位有符号数相乘是否溢出 64 位有符号上限
function IsInt64MulOverflow(a, b: int64): boolean;
var
  T: int64;
begin
  T      := a * b;
  Result := (b <> 0) and ((T div b) <> a);
end;
 
// 指针类型转换成整型,支持 32/64 位
function PointerToInteger(P: Pointer): integer;
begin
{$IFDEF CPU64BITS}
  // 先这么写,利用 Pointer 的低 32 位存 Integer
  Result := Integer(P);
{$ELSE}
  Result := integer(P);
{$ENDIF}
end;
 
// 整型转换成指针类型,支持 32/64 位
function IntegerToPointer(i: integer): Pointer;
begin
{$IFDEF CPU64BITS}
  // 先这么写,利用 Pointer 的低 32 位存 Integer
  Result := Pointer(I);
{$ELSE}
  Result := Pointer(i);
{$ENDIF}
end;
 
// 求 Int64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0
function Int64NonNegativeAddMod(a, b, N: int64): int64;
begin
  if IsInt64AddOverflow(a, b) then // 如果加起来溢出 Int64
    begin
    if a > 0 then
      begin
      // A 和 B 都大于 0,采用 UInt64 相加取模(和未溢出 UInt64 上限),注意 N 未溢出 Int64 因此取模结果小于 Int64 上限,不会变成负值
      Result := UInt64NonNegativeAddMod(a, b, N);
      end
    else
      begin
      // A 和 B 都小于 0,取反后采用 UInt64 相加取模(反后的和未溢出 UInt64 上限),模再被除数减一下
{$IFDEF SUPPORT_UINT64}
      Result := UInt64(N) - UInt64NonNegativeAddMod(-A, -B, N);
{$ELSE}
      Result := N - UInt64NonNegativeAddMod(-a, -b, N);
{$ENDIF}
      end;
    end
  else // 不溢出,直接加起来求余
    Result := Int64NonNegativeMod(a + b, N);
end;
 
// 求 UInt64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0
function UInt64NonNegativeAddMod(a, b, N: TUInt64): TUInt64;
var
  c, d: TUInt64;
begin
  if IsUInt64AddOverflow(a, b) then // 如果加起来溢出
    begin
    c := UInt64Mod(a, N);  // 就各自求模
    d := UInt64Mod(b, N);
    if IsUInt64AddOverflow(c, d) then
      begin
      // 如果还是溢出,说明模比两个加数都大,各自求模没用。
      // 至少有一个加数大于等于 2^63,N 至少是 2^63 + 1
      // 和 = 溢出结果 + 2^64
      // 和 mod N = 溢出结果 mod N + (2^64 - 1) mod N) + 1
      // 这里 N 至少是 2^63 + 1,溢出结果最多是 2^64 - 2,所以前两项相加不会溢出,可以直接相加后减一再求模
      Result := UInt64Mod(UInt64Mod(a + b, N) + UInt64Mod(CN_MAX_TUINT64, N) + 1, N);
      end
    else
      Result := UInt64Mod(c + d, N);
    end
  else
    begin
    Result := UInt64Mod(a + b, N);
    end;
end;
 
function Int64NonNegativeMulMod(a, b, N: int64): int64;
var
  Neg: boolean;
begin
  if N <= 0 then
    raise EDivByZero.Create(SDivByZero);
 
  // 范围小就直接算
  if not IsInt64MulOverflow(a, b) then
    begin
    Result := a * b mod N;
    if Result < 0 then
      Result := Result + N;
    Exit;
    end;
 
  // 调整符号到正
  Result := 0;
  if (a = 0) or (b = 0) then
    Exit;
 
  Neg := False;
  if (a < 0) and (b > 0) then
    begin
    a   := -a;
    Neg := True;
    end
  else if (a > 0) and (b < 0) then
      begin
      b   := -b;
      Neg := True;
      end
    else if (a < 0) and (b < 0) then
        begin
        a := -a;
        b := -b;
        end;
 
  // 移位循环算
  while b <> 0 do
    begin
    if (b and 1) <> 0 then
      Result := ((Result mod N) + (a mod N)) mod N;
 
    a := a shl 1;
    if a >= N then
      a := a mod N;
 
    b := b shr 1;
    end;
 
  if Neg then
    Result := N - Result;
end;
 
function UInt64NonNegativeMulMod(a, b, N: TUInt64): TUInt64;
begin
  Result := 0;
  if (UInt64Compare(a, CN_MAX_UINT32) <= 0) and
    (UInt64Compare(b, CN_MAX_UINT32) <= 0) then
    begin
    Result := UInt64Mod(a * b, N); // 足够小的话直接乘后求模
    end
  else
    begin
    while b <> 0 do
      begin
      if (b and 1) <> 0 then
        Result := UInt64NonNegativeAddMod(Result, a, N);
 
      a := UInt64NonNegativeAddMod(a, a, N);
      // 不能用传统算法里的 A := A shl 1,大于 N 后再 mod N,因为会溢出
 
      b := b shr 1;
      end;
    end;
end;
 
// 封装的非负求余函数,也就是余数为负时,加个除数变正,调用者需保证 P 大于 0
function Int64NonNegativeMod(N: int64; P: int64): int64;
begin
  if P <= 0 then
    raise EDivByZero.Create(SDivByZero);
 
  Result := N mod P;
  if Result < 0 then
    Inc(Result, P);
end;
 
// Int64 的非负整数指数幂
function Int64NonNegativPower(N: int64; Exp: integer): int64;
var
  T: int64;
begin
  if Exp < 0 then
    raise ERangeError.Create(SRangeError)
  else if Exp = 0 then
      begin
      if N <> 0 then
        Result := 1
      else
        raise EDivByZero.Create(SDivByZero);
      end
    else if Exp = 1 then
        Result := N
      else
        begin
        Result := 1;
        T      := N;
 
        while Exp > 0 do
          begin
          if (Exp and 1) <> 0 then
            Result := Result * T;
 
          Exp := Exp shr 1;
          T   := T * T;
          end;
        end;
end;
 
function Int64NonNegativeRoot(N: int64; Exp: integer): int64;
var
  i: integer;
  x: int64;
  X0, x1: extended;
begin
  if (Exp < 0) or (N < 0) then
    raise ERangeError.Create(SRangeError)
  else if Exp = 0 then
      raise EDivByZero.Create(SDivByZero)
    else if (N = 0) or (N = 1) then
        Result := N
      else if Exp = 2 then
          Result := UInt64Sqrt(N)
        else
          begin
          // 牛顿迭代法求根
          i := GetUInt64HighBits(N) + 1; // 得到大约 Log2 N 的值
          i := (i div Exp) + 1;
          x := 1 shl i;                  // 得到一个较大的 X0 值作为起始值
 
          X0 := x;
          x1 := X0 - (Power(X0, Exp) - N) / (Exp * Power(X0, Exp - 1));
 
          while True do
            begin
            if (Trunc(X0) = Trunc(x1)) and (Abs(X0 - x1) < 0.001) then
              begin
              Result := Trunc(x1); // Trunc 只支持 Int64,超界了会出错
              Exit;
              end;
 
            X0 := x1;
            x1 := X0 - (Power(X0, Exp) - N) / (Exp * Power(X0, Exp - 1));
            end;
          end;
end;
 
function UInt64NonNegativPower(N: TUInt64; Exp: integer): TUInt64;
var
  T, RL, RH: TUInt64;
begin
  if Exp < 0 then
    raise ERangeError.Create(SRangeError)
  else if Exp = 0 then
      begin
      if N <> 0 then
        Result := 1
      else
        raise EDivByZero.Create(SDivByZero);
      end
    else if Exp = 1 then
        Result := N
      else
        begin
        Result := 1;
        T      := N;
 
        while Exp > 0 do
          begin
          if (Exp and 1) <> 0 then
            begin
            UInt64MulUInt64(Result, T, RL, RH);
            Result := RL;
            end;
 
          Exp := Exp shr 1;
          UInt64MulUInt64(T, T, RL, RH);
          T := RL;
          end;
        end;
end;
 
function UInt64NonNegativeRoot(N: TUInt64; Exp: integer): TUInt64;
var
  i: integer;
  x: TUInt64;
  XN, X0, x1: extended;
begin
  if Exp < 0 then
    raise ERangeError.Create(SRangeError)
  else if Exp = 0 then
      raise EDivByZero.Create(SDivByZero)
    else if (N = 0) or (N = 1) then
        Result := N
      else if Exp = 2 then
          Result := UInt64Sqrt(N)
        else
          begin
          // 牛顿迭代法求根
          i := GetUInt64HighBits(N) + 1; // 得到大约 Log2 N 的值
          i := (i div Exp) + 1;
          x := 1 shl i;                  // 得到一个较大的 X0 值作为起始值
 
          X0 := UInt64ToExtended(x);
          XN := UInt64ToExtended(N);
          x1 := X0 - (Power(X0, Exp) - XN) / (Exp * Power(X0, Exp - 1));
 
          while True do
            begin
            if (ExtendedToUInt64(X0) = ExtendedToUInt64(x1)) and (Abs(X0 - x1) < 0.001) then
              begin
              Result := ExtendedToUInt64(x1);
              Exit;
              end;
 
            X0 := x1;
            x1 := X0 - (Power(X0, Exp) - XN) / (Exp * Power(X0, Exp - 1));
            end;
          end;
end;
 
function IsUInt128BitSet(Lo, Hi: TUInt64; N: integer): boolean;
begin
  if N < 64 then
    Result := (Lo and (TUInt64(1) shl N)) <> 0
  else
    begin
    Dec(N, 64);
    Result := (Hi and (TUInt64(1) shl N)) <> 0;
    end;
end;
 
procedure SetUInt128Bit(var Lo, Hi: TUInt64; N: integer);
begin
  if N < 64 then
    Lo := Lo or (TUInt64(1) shl N)
  else
    begin
    Dec(N, 64);
    Hi := Hi or (TUInt64(1) shl N);
    end;
end;
 
procedure ClearUInt128Bit(var Lo, Hi: TUInt64; N: integer);
begin
  if N < 64 then
    Lo := Lo and not (TUInt64(1) shl N)
  else
    begin
    Dec(N, 64);
    Hi := Hi and not (TUInt64(1) shl N);
    end;
end;
 
function UnsignedAddWithLimitRadix(a, b, c: cardinal; var r: cardinal;
L, H: cardinal): cardinal;
begin
  r := a + b + c;
  if r > H then         // 有进位
    begin
    a := H - L + 1;     // 得到进制
    b := r - L;         // 得到超出 L 的值
 
    Result := b div a;  // 超过进制的第几倍就进几
    r      := L + (b mod a); // 去掉进制后的余数,加上下限
    end
  else
    Result := 0;
end;
 
procedure InternalQuickSort(Mem: Pointer; L, r: integer; ElementByteSize: integer;
CompareProc: TCnMemSortCompareProc);
var
  i, j, P: integer;
begin
  repeat
    i := L;
    j := r;
    P := (L + r) shr 1;
    repeat
      while CompareProc(Pointer(TCnNativeInt(Mem) + i * ElementByteSize),
          Pointer(TCnNativeInt(Mem) + P * ElementByteSize), ElementByteSize) < 0 do
        Inc(i);
      while CompareProc(Pointer(TCnNativeInt(Mem) + j * ElementByteSize),
          Pointer(TCnNativeInt(Mem) + P * ElementByteSize), ElementByteSize) > 0 do
        Dec(j);
 
      if i <= j then
        begin
        MemorySwap(Pointer(TCnNativeInt(Mem) + i * ElementByteSize),
          Pointer(TCnNativeInt(Mem) + j * ElementByteSize), ElementByteSize);
 
        if P = i then
          P := j
        else if P = j then
            P := i;
        Inc(i);
        Dec(j);
        end;
    until i > j;
 
    if L < j then
      InternalQuickSort(Mem, L, j, ElementByteSize, CompareProc);
    L := i;
  until i >= r;
end;
 
function DefaultCompareProc(p1, p2: Pointer; ElementByteSize: integer): integer;
begin
  Result := MemoryCompare(p1, p2, ElementByteSize);
end;
 
procedure MemoryQuickSort(Mem: Pointer; ElementByteSize: integer;
ElementCount: integer; CompareProc: TCnMemSortCompareProc);
begin
  if (Mem <> nil) and (ElementCount > 0) and (ElementCount > 0) then
    begin
    if Assigned(CompareProc) then
      InternalQuickSort(Mem, 0, ElementCount - 1, ElementByteSize, CompareProc)
    else
      InternalQuickSort(Mem, 0, ElementCount - 1, ElementByteSize, @DefaultCompareProc);
    end;
end;
 
{$IFDEF COMPILER5}
 
function BoolToStr(Value: Boolean; UseBoolStrs: Boolean): string;
begin
  if UseBoolStrs then
  begin
    if Value then
      Result := 'True'
    else
      Result := 'False';
  end
  else
  begin
    if Value then
      Result := '-1'
    else
      Result := '0';
  end;
end;
 
{$ENDIF}
 
initialization
FByteOrderIsBigEndian := CurrentByteOrderIsBigEndian;
 
end.

  

posted @   心痕如丝  阅读(99)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示