-
Notifications
You must be signed in to change notification settings - Fork 14
/
bits.h
73 lines (61 loc) · 1.44 KB
/
bits.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* SPDX-License-Identifier: MIT */
/*
* Helper functions for manipulation & testing of integer values
* like zero or sign-extensions.
*
* Copyright (C) 2017 Luc Van Oostenryck
*
*/
#ifndef BITS_H
#define BITS_H
static inline unsigned long long sign_bit(unsigned size)
{
return 1ULL << (size - 1);
}
static inline unsigned long long sign_mask(unsigned size)
{
unsigned long long sbit = sign_bit(size);
return sbit - 1;
}
static inline unsigned long long bits_mask(unsigned size)
{
unsigned long long sbit = sign_bit(size);
return sbit | (sbit - 1);
}
static inline long long zero_extend(long long val, unsigned size)
{
return val & bits_mask(size);
}
static inline long long sign_extend(long long val, unsigned size)
{
if (val & sign_bit(size))
val |= ~sign_mask(size);
return val;
}
///
// sign extend @val but only if exactly representable
static inline long long sign_extend_safe(long long val, unsigned size)
{
unsigned long long mask = bits_mask(size);
if (!(val & ~mask))
val = sign_extend(val, size);
return val;
}
static inline long long bits_extend(long long val, unsigned size, int is_signed)
{
val = zero_extend(val, size);
if (is_signed)
val = sign_extend(val, size);
return val;
}
static inline int is_power_of_2(long long val)
{
return val && !(val & (val - 1));
}
///
// log base 2 of an exact power-of-2
static inline int log2_exact(unsigned long long val)
{
return 8 * sizeof(val) - __builtin_clzl(val) - 1;
}
#endif