Mbed OS Reference
Loading...
Searching...
No Matches
mbed_math_helpers.h
1/* mbed Microcontroller Library
2 * Copyright (c) 2026 Jamie Smith
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#pragma once
19
20#include <stdint.h>
21
22/**
23 * @brief Check whether an integer is an exact power of two.
24 */
25// from https://stackoverflow.com/a/600306/7083698
26static inline bool mbed_is_power_of_two(const uint32_t x)
27{
28 return x > 0 && (x & (x - 1)) == 0;
29}
30
31/**
32 * @brief Get the log2 of an integer.
33 *
34 * Rounds down to the nearest power of 2, i.e. \c mbed_integer_log_2(3) is 1.
35 */
36static inline uint32_t mbed_integer_log_2(uint32_t x)
37{
38 return sizeof(uint32_t) * 8 - 1 - __builtin_clz(x);
39}
40
41/**
42 * @brief Align an address (\c addr) to a given \c alignment by adding between 0 and \c alignment-1 bytes to it.
43 */
44static inline void *mbed_align_up_to(void *addr, size_t alignment)
45{
46 // Use integer division to divide the address down to the alignment size, which
47 // rounds to the block before the given address.
48 // So that we always go one cache line back even if the given address is on the start of a block,
49 // subtract 1.
50 ptrdiff_t prev_block_start = ((ptrdiff_t)(addr) - 1) / alignment;
51
52 // Now we just have to multiply up again to get an address (adding 1 to go forward by 1 block)
53 return (void *)((prev_block_start + 1) * alignment);
54}