File: bits.h

package info (click to toggle)
libdisplay-info 0.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,460 kB
  • sloc: ansic: 10,055; python: 294; sh: 131; makefile: 3
file content (40 lines) | stat: -rw-r--r-- 679 bytes parent folder | download | duplicates (5)
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
#ifndef BITS_H
#define BITS_H

/**
 * Utility functions to operate on bits.
 */

#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

/**
 * Check whether a byte has a bit set.
 */
static inline bool
has_bit(uint8_t val, size_t index)
{
	return val & (1 << index);
}

/**
 * Extract a bit range from a byte.
 *
 * Both offsets are inclusive, start from zero, and high must be greater than low.
 */
static inline uint8_t
get_bit_range(uint8_t val, size_t high, size_t low)
{
	size_t n;
	uint8_t bitmask;

	assert(high <= 7 && high >= low);

	n = high - low + 1;
	bitmask = (uint8_t) ((1 << n) - 1);
	return (uint8_t) (val >> low) & bitmask;
}

#endif