简体   繁体   English

C宏获得大于给定数的2的最小幂

[英]C macro to get the smallest power of two greater than a given number

I need a C macro to get the smallest of power two greater than a given number. 我需要一个C宏来获得比给定数字大2的最小幂。

For example, FIRSTFREEBIT(0x16) (binary 1_0110 ) must be equal to 0x20 . 例如, FIRSTFREEBIT(0x16) (二进制1_0110 )必须等于0x20

I am going to use it as: 我将其用作:

#include <someheader.h> // defines SOME_X and SOME_Y
enum {
     x = SOME_X,
     y = SOME_Y,
     z = FIRSTFREEBIT(x|y),
     t = z << 1,
};

A similar, but slightly different SO question: Algorithm for finding the smallest power of two that's greater or equal to a given value 一个类似但略有不同的SO问题: 用于查找两个大于或等于给定值的最小幂的算法

Here's my code, you are welcome to invent something better: 这是我的代码,欢迎您发明更好的东西:

#define __OR_RSHIFT__(n,x) ((x)|(x)>>n)
#define FIRST_UNUSED_BIT(x) (1+__OR_RSHIFT__(16,__OR_RSHIFT__(8,__OR_RSHIFT__(4,__OR_RSHIFT__(2,__OR_RSHIFT__(1,x))))))

Look at the __builtin_clz GCC intrinsic. 查看__builtin_clz GCC内部函数。 It will give you the number of leading zero bits, which could be used to determine the position of the first bit set. 它将为您提供前导零位的数量,可用于确定第一个位集的位置。 Then do a left bit shift of 1 , times the position. 然后将位置左移1倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C 函数从按递增顺序排序的数组中返回大于给定数字的最小数字的索引 - C function that returns index of smallest number greater than a given number from an array sorted in increased order 使用C的排序数组中最小数字大于给定数字的数组索引 - Array index of smallest number greater than a given number in a sorted array using C C宏:获得整数常量的最小类型 - C Macro: get smallest type for an integer constant 给定数组中的最小奇数 - Smallest odd number in given array 用C编写一个程序,该程序输出大于或等于n且所有数字均为偶数的最小自然数 - Write a program in C that outputs the smallest natural number greater or equal to n whose all digits are even 如何在给定数值宏值的情况下让C找到宏标识符? - How to get C to find the macro identifier given the numeric macro value? 有没有一种简单的方法来获得两个数字的幂? - Is there an easy way to get which power of two a number is? 打印给定 4 位数字的副本,但每个素数后跟比它大 1 的数字 - Printing a copy of a given 4 digit number but every prime digit is followed by the number which is one greater than it C比较两个指针大于一个是否为null - C compare two pointers greater than if one is null 大于C中的功能 - Greater than function in C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM