将一个Int转换为一个Int数组,该数组指示C中位的位置
所以如果我有一个int,比如说将一个Int转换为一个Int数组,该数组指示C中位的位置,c,bit-manipulation,built-in,C,Bit Manipulation,Built In,所以如果我有一个int,比如说000010101101001,它应该变成一个数组,像{0,3,5,6,8,11}。我现在使用的是一个使用clz(计数前导零)和位掩码的卷积系统,但我怀疑应该存在更好的系统 我使用的是i7,使用的是gcc,使用SIMD/SSE内置被认为是一件好事。这如何(应该适用于无符号整数): 我想有更好的方法可以做到这一点。这个方法怎么样(应该适用于无符号整数): 我想有更好的方法可以做到这一点。你可以做以下事情: void bit2arr(int *result, size_
000010101101001
,它应该变成一个数组,像{0,3,5,6,8,11}
。我现在使用的是一个使用clz(计数前导零)和位掩码的卷积系统,但我怀疑应该存在更好的系统
我使用的是i7,使用的是gcc,使用SIMD/SSE内置被认为是一件好事。这如何(应该适用于无符号整数):
我想有更好的方法可以做到这一点。这个方法怎么样(应该适用于无符号整数):
我想有更好的方法可以做到这一点。你可以做以下事情:
void bit2arr(int *result, size_t len, unsigned val) {
int count = 0;
while (val && len) {
// add bit to array if needed
if (val & 1) {
*result++ = count;
--len; // Don't overflow output
}
// Increment counter regardless
++count;
// remove bit and bitshift
val &= (~0 ^ 1);
val >>= 1;
}
}
一次取一位,如果位置非零,则将其保存到数组中
我将其用于:
#include <stdio.h>
#include <string.h>
static const unsigned val = 2409;
int main() {
int result[32];
memset(result, 0, sizeof(result));
bit2arr(result, 32, val);
for (int i = 0; i < 32; ++i) {
printf("%s%d", i ? ", " : "", result[i]);
}
printf("\n");
return 0;
}
#包括
#包括
静态常量无符号val=2409;
int main(){
int结果[32];
memset(result,0,sizeof(result));
bit2arr(结果,32,val);
对于(int i=0;i<32;++i){
printf(“%s%d”,i?”,“:”,结果[i]);
}
printf(“\n”);
返回0;
}
其中给出:
0,3,5,6,8,11,0
让函数返回结果数组的大小应该很容易。您可以执行以下操作:
void bit2arr(int *result, size_t len, unsigned val) {
int count = 0;
while (val && len) {
// add bit to array if needed
if (val & 1) {
*result++ = count;
--len; // Don't overflow output
}
// Increment counter regardless
++count;
// remove bit and bitshift
val &= (~0 ^ 1);
val >>= 1;
}
}
size_t bit2arr(char *result, unsigned val) {
size_t pos, cnt;
for (pos=cnt=0; val; val >>=1, pos++) {
if (val & 1) result [cnt++] = pos;
}
return cnt; /* number of 1 bits := number of valid positions in result[] */
}
一次取一位,如果位置非零,则将其保存到数组中
我将其用于:
#include <stdio.h>
#include <string.h>
static const unsigned val = 2409;
int main() {
int result[32];
memset(result, 0, sizeof(result));
bit2arr(result, 32, val);
for (int i = 0; i < 32; ++i) {
printf("%s%d", i ? ", " : "", result[i]);
}
printf("\n");
return 0;
}
#包括
#包括
静态常量无符号val=2409;
int main(){
int结果[32];
memset(result,0,sizeof(result));
bit2arr(结果,32,val);
对于(int i=0;i<32;++i){
printf(“%s%d”,i?”,“:”,结果[i]);
}
printf(“\n”);
返回0;
}
其中给出:
0,3,5,6,8,11,0
让函数返回结果数组的大小应该很容易。谢谢,现在就试试。它将我的计算速度提高了12%,非常好(节省了半天)。我对你的怀疑很感兴趣:)谢谢,现在试试这个。它把我的计算速度提高了12%,非常好(节省了半天)。我对你的怀疑很感兴趣:)+1,我喜欢将位移位滚动到循环条件+1,我喜欢将位移位滚动到循环条件
size_t bit2arr(char *result, unsigned val) {
size_t pos, cnt;
for (pos=cnt=0; val; val >>=1, pos++) {
if (val & 1) result [cnt++] = pos;
}
return cnt; /* number of 1 bits := number of valid positions in result[] */
}