tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

55 lignes · 1849 octetsBrut · Historique
1/// Bit operations on `Int` (ADR 0035), for binary formats, hashes, masks
2/// and random generators.
3///
4/// int.and(0b1100, 0b1010) // 8
5/// int.shift_left(1, 64) // 18446744073709551616 (a big integer)
6/// int.shift_right(-5, 1) // -3 (rounds towards minus infinity)
7///
8/// An `Int` behaves as two's complement with infinite sign extension, as in
9/// Python: `-1` is all ones, so `int.and(n, -1) == n` and `int.not(n)` is
10/// `-n - 1`. The result is the same whether an operand is small or a big
11/// integer. A mask above 62 bits can't be a literal (literals are 63-bit):
12/// compute it, `int.shift_left(1, 64) - 1`. For wrapping 64-bit arithmetic,
13/// see `std/u64`.
14
15/// The bits set in both.
16@extern c "tl_int_and"
17pub fn and :: a: Int b: Int -> Int
18
19/// The bits set in either.
20@extern c "tl_int_or"
21pub fn or :: a: Int b: Int -> Int
22
23/// The bits set in exactly one.
24@extern c "tl_int_xor"
25pub fn xor :: a: Int b: Int -> Int
26
27/// Every bit flipped: `-n - 1`.
28@extern c "tl_int_not"
29pub fn not :: n: Int -> Int
30
31/// `n * 2^k`. Panics if `k` is negative, or if it is `2^32` or more and `n`
32/// is not 0 (the result would not fit in memory).
33@extern c "tl_int_shift_left"
34pub fn shift_left :: n: Int k: Int -> Int
35
36/// `n / 2^k`, rounded towards minus infinity: `shift_right(-1, k)` is `-1`.
37/// Panics if `k` is negative.
38@extern c "tl_int_shift_right"
39pub fn shift_right :: n: Int k: Int -> Int
40
41/// The number of bits of `|n|`: 0 for 0, 1 for 1 and -1, 8 for 255.
42@extern c "tl_int_bit_length"
43pub fn bit_length :: n: Int -> Int
44
45/// Whether bit `k` (0 is the lowest) of `n` is set.
46pub fn bit :: n: Int k: Int -> Bool
47{
48 and (shift_right n k) 1 == 1
49}
50
51/// The low `bits` bits of `n`: `n` modulo `2^bits`, in `[0, 2^bits)`.
52pub fn low_bits :: n: Int bits: Int -> Int
53{
54 and n (shift_left 1 bits - 1)
55}