![](/img/trans.png)
[英]Bits twiddling hack: most efficient way to remove one bit every n bits?
[英]Bit hack: Expanding bits
我試圖將uint16_t
輸入轉換為uint32_t
位掩碼。 輸入中的一位在輸出位掩碼中切換兩位。 以下是將4位輸入轉換為8位位掩碼的示例:
Input Output
ABCDb -> AABB CCDDb
A,B,C,D are individual bits
Example outputs:
0000b -> 0000 0000b
0001b -> 0000 0011b
0010b -> 0000 1100b
0011b -> 0000 1111b
....
1100b -> 1111 0000b
1101b -> 1111 0011b
1110b -> 1111 1100b
1111b -> 1111 1111b
有沒有一種方法來實現這種行為?
Binary Magic Numbers的交錯位包含了線索:
uint32_t expand_bits(uint16_t bits)
{
uint32_t x = bits;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
return x | (x << 1);
}
的前四個步驟連續地交織所述源位2的8組,4個,1位用零個比特,導致00AB00CD
在第一步驟之后, 0A0B0C0D
之后的第二步驟中,依此類推。 最后一步然后將每個偶數位(包含原始源位)復制到相鄰奇數位中,從而實現所需的位排列。
許多變體都是可能的。 最后一步也可以編碼為x + (x << 1)
或3 * x
。 |
前四個步驟中的運算符可以由^
運算符替換。 掩碼也可以修改,因為一些位自然為零,不需要清除。 在一些處理器上,短掩模可以作為中間體結合到機器指令中,減少了構造和/或加載掩模常數的努力。 增加無序處理器的指令級並行性並針對具有shift-add或整數乘加指令的那些進行優化也可能是有利的。 包含各種這些想法的一個代碼變體是:
uint32_t expand_bits (uint16_t bits)
{
uint32_t x = bits;
x = (x ^ (x << 8)) & ~0x0000FF00;
x = (x ^ (x << 4)) & ~0x00F000F0;
x = x ^ (x << 2);
x = ((x & 0x22222222) << 1) + (x & 0x11111111);
x = (x << 1) + x;
return x;
}
將4位輸入映射到8位輸出的最簡單方法是使用16個輸入表。 那么這只是從uint16_t
一次提取4位,進行表查找,並將8位值插入輸出的問題。
uint32_t expandBits( uint16_t input )
{
uint32_t table[16] = {
0x00, 0x03, 0x0c, 0x0f,
0x30, 0x33, 0x3c, 0x3f,
0xc0, 0xc3, 0xcc, 0xcf,
0xf0, 0xf3, 0xfc, 0xff
};
uint32_t output;
output = table[(input >> 12) & 0xf] << 24;
output |= table[(input >> 8) & 0xf] << 16;
output |= table[(input >> 4) & 0xf] << 8;
output |= table[ input & 0xf];
return output;
}
這在性能和可讀性之間提供了適當的折衷。 它沒有cmaster的over-the-top查找解決方案的性能,但它肯定比thndrwrks神奇的神秘解決方案更容易理解。 因此,它提供了一種可應用於更多種類問題的技術,即使用小型查找表來解決更大的問題。
如果你想得到一些相對速度的估計,一些社區維基測試代碼。 根據需要調整。
void f_cmp(uint32_t (*f1)(uint16_t x), uint32_t (*f2)(uint16_t x)) {
uint16_t x = 0;
do {
uint32_t y1 = (*f1)(x);
uint32_t y2 = (*f2)(x);
if (y1 != y2) {
printf("%4x %8lX %8lX\n", x, (unsigned long) y1, (unsigned long) y2);
}
} while (x++ != 0xFFFF);
}
void f_time(uint32_t (*f1)(uint16_t x)) {
f_cmp(expand_bits, f1);
clock_t t1 = clock();
volatile uint32_t y1 = 0;
unsigned n = 1000;
for (unsigned i = 0; i < n; i++) {
uint16_t x = 0;
do {
y1 += (*f1)(x);
} while (x++ != 0xFFFF);
}
clock_t t2 = clock();
printf("%6llu %6llu: %.6f %lX\n", (unsigned long long) t1,
(unsigned long long) t2, 1.0 * (t2 - t1) / CLOCKS_PER_SEC / n,
(unsigned long) y1);
fflush(stdout);
}
int main(void) {
f_time(expand_bits);
f_time(expandBits);
f_time(remask);
f_time(javey);
f_time(thndrwrks_expand);
// now in the other order
f_time(thndrwrks_expand);
f_time(javey);
f_time(remask);
f_time(expandBits);
f_time(expand_bits);
return 0;
}
結果
0 280: 0.000280 FE0C0000 // fast
280 702: 0.000422 FE0C0000
702 1872: 0.001170 FE0C0000
1872 3026: 0.001154 FE0C0000
3026 4399: 0.001373 FE0C0000 // slow
4399 5740: 0.001341 FE0C0000
5740 6879: 0.001139 FE0C0000
6879 8034: 0.001155 FE0C0000
8034 8470: 0.000436 FE0C0000
8486 8751: 0.000265 FE0C0000
這是一個有效的實現:
uint32_t remask(uint16_t x)
{
uint32_t i;
uint32_t result = 0;
for (i=0;i<16;i++) {
uint32_t mask = (uint32_t)x & (1U << i);
result |= mask << (i);
result |= mask << (i+1);
}
return result;
}
在循環的每次迭代中,來自uint16_t
有問題的位被屏蔽並存儲。
然后將該位移位其位位置並對結果進行“或”運算,然后再次移位其位加1並對結果進行“或”運算。
一個簡單的循環。 也許不夠點hacky?
uint32_t thndrwrks_expand(uint16_t x) {
uint32_t mask = 3;
uint32_t y = 0;
while (x) {
if (x&1) y |= mask;
x >>= 1;
mask <<= 2;
}
return y;
}
嘗試另一個快兩倍。 仍然是655/272,與expand_bits()
一樣慢。 似乎是最快的16循環迭代解決方案。
uint32_t thndrwrks_expand(uint16_t x) {
uint32_t y = 0;
for (uint16_t mask = 0x8000; mask; mask >>= 1) {
y <<= 1;
y |= x&mask;
}
y *= 3;
return y;
}
如果您關注的是性能和簡單性,那么最好使用大型查找表(每個4字節的64k條目)。 有了它,您幾乎可以使用任何您喜歡的算法來生成表,查找將只是一個內存訪問。
如果該表太大而不適合您,您可以拆分它。 例如,您可以使用8位查找表,其中256個條目各有2個字節。 有了它,您只需兩次查找即可執行整個操作。 額外的是,這種方法允許類型懲罰技巧,以避免使用位操作分割地址的麻煩:
//Implementation defined behavior ahead:
//Works correctly for both little and big endian machines,
//however, results will be wrong on a PDP11...
uint32_t getMask(uint16_t input) {
assert(sizeof(uint16_t) == 2);
assert(sizeof(uint32_t) == 4);
static const uint16_t lookupTable[256] = { 0x0000, 0x0003, 0x000c, 0x000f, ... };
unsigned char* inputBytes = (unsigned char*)&input; //legal because we type-pun to char, but the order of the bytes is implementation defined
char outputBytes[4];
uint16_t* outputShorts = (uint16_t*)outputBytes; //legal because we type-pun from char, but the order of the shorts is implementation defined
outputShorts[0] = lookupTable[inputBytes[0]];
outputShorts[1] = lookupTable[inputBytes[1]];
uint32_t output;
memcpy(&output, outputBytes, 4); //can't type-pun directly from uint16 to uint32_t due to strict aliasing rules
return output;
}
上面的代碼通過僅轉換為/來自char
來解決嚴格別名規則,這是嚴格別名規則的顯式異常。 它還通過以與輸入分割相同的順序構建結果來解決小/大端字節順序的影響。 但是,它仍然暴露出實現定義的行為:一台機器的字節順序1, 0, 3, 2
,或其他中間端的訂單 ,會悄悄地產生錯誤的結果(有其實一直這樣的CPU如PDP11 ...)。
當然,您可以進一步拆分查找表,但我懷疑這對您有什么好處。
試試這個,其中input16
是uint16_t輸入掩碼:
uint32_t input32 = (uint32_t) input16;
uint32_t result = 0;
uint32_t i;
for(i=0; i<16; i++)
{
uint32_t bit_at_i = (input32 & (((uint32_t)1) << i)) >> i;
result |= ((bit_at_i << (i*2)) | (bit_at_i << ((i*2)+1)));
}
// result is now the 32 bit expanded mask
我的解決方案是在主流x86 PC上運行,簡單而通用。 我沒有寫這個來競爭最快和/或最短的實現。 這只是解決OP提交的問題的另一種方法。
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define BITS_TO_EXPAND (4U)
#define SIZE_MAX (256U)
static bool expand_uint(unsigned int *toexpand,unsigned int *expanded);
int main(void)
{
unsigned int in = 12;
unsigned int out = 0;
bool success;
char buff[SIZE_MAX];
success = expand_uint(&in,&out);
if(false == success)
{
(void) puts("Error: expand_uint failed");
return EXIT_FAILURE;
}
(void) snprintf(buff, (size_t) SIZE_MAX,"%u expanded is %u\n",in,out);
(void) fputs(buff,stdout);
return EXIT_SUCCESS;
}
/*
** It expands an unsigned int so that every bit in a nibble is copied twice
** in the resultant number. It returns true on success, false otherwise.
*/
static bool expand_uint(unsigned int *toexpand,unsigned int *expanded)
{
unsigned int i;
unsigned int shifts = 0;
unsigned int mask;
if(NULL == toexpand || NULL == expanded)
{
return false;
}
*expanded = 0;
for(i = 0; i < BIT_TO_EXPAND; i++)
{
mask = (*toexpand >> i) & 1;
*expanded |= (mask << shifts);
++shifts;
*expanded |= (mask << shifts);
++shifts;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.