[英]Get highest number with n bits
我想在 C++ 中獲得 n 位的最高數字。我已經編寫了這段代碼,但也許有更有效的方法。
int A = 22; // 10110
int max = pow(2, (int) log2(A) + 1) - 1; // returns 31 (11111)
此代碼計算 A 的位數的 2 次方並減去 1。
編輯
由於問題似乎不清楚,這里有一些更多的例子來幫助理解我想要達到的結果。
1000
=> 1111
1010
=> 1111
100001
=> 111111
111
=> 111
首先,使用How to do an integer log2() in C++? . 然后將 position 比最高位多一位,然后減一以獲得所有位設置。
int A = 22;
unsigned max = (1u << std::bit_width((unsigned)A)) - 1;
注意:這將在UINT_MAX >> 1
左右起作用,因為1u <<
會溢出。
聽起來像是一個 Bit Twiddling 問題。 這是基於https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 ,只是沒有最后的增量。
unsigned int v;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
不過,這僅適用於 32 位數字,並且未經測試。
通常的方法是將 2 乘以 A 的位數並減去 1,這樣寫和讀起來要簡單得多。
Formula: (1 << nb_bits) - 1
// example: mask lower 8 bits, same as highest number in 8 bits.
constexpr int mask = (1 << 8) - 1; // 255
// <=> mask = 0b1'0000'0000 - 1 in hex: 0x0100 - 1
// <=> mash = 0b0'1111'1111 in hex: 0x00FF
// for numbers made of up to 127 bits, use 128 bits integer:
// on gcc
__uint128_t largest_in_n_bits(int n) {
assert(n < 128);
return (__uint128_t(1) << n) - 1;
}
沒有任何 function 電話,我會提出這個算法:
int a = 22;
short count = 0;
while(a != 0){
a >>= 1;
++count;
}
for(int i=0; i<count; ++i){
a |= 1;
a <<= 1;
}
a >>= 1;
// a is now 31
可能有一種更經典的方法來做到這一點,但這種方法只使用位移。
我寫了這段代碼,但也許有更有效的方法。
我假設問題是“可以改進此代碼”嗎?
是的,它可以。
你的代碼是做什么的
A
隱式轉換為double
,因為log2(double)
采用double
參數。log2(double)
function 取該(double)A
的以 2 為底的對數。double
向下舍入到最接近的int
,然后加 1double
,然后使用pow(double, double)
function 來近似 2.0 ** 那個。 所以,首先,很明顯, pow
對你的情況毫無用處。 使用移位; 1 << k
將 1 左移k
位位置; 結果是 2**k。
然后,檢測 integer 中的最高設置位是一個已解決的問題: 在 C 中找到 integer 中的最高設置位 (msb) 的最快/最有效的方法是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.