问题描述
我要救8布尔到一个字节,然后将其保存到一个文件中(这项工作必须为一个非常大的数据来完成),我用下面的code,但我不知道它是最好的一个(在速度和空间方面):
I want to save 8 boolean to one byte and then save it to a file(this work must be done for a very large data), I've used the following code but I'm not sure it is the best one(in terms of speed and space):
int bits[]={1,0,0,0,0,1,1,1};
char a='\0';
for (int i=0;i<8;i++){
a=a<<1;
a+=bits[i]
}
//and then save "a"
谁能给我一个更好的code(更高的速度)?
can anyone give me a better code(more speed) ?
推荐答案
如果你不介意使用上证所内部函数,那么的是一个很好的选择。它采用16字节,但你可以设置其他为零。
If you don't mind using SSE intrinsics, then _mm_movemask_epi8 is an excellent fit. It uses 16 bytes, but you can just set the others to zero.
例如(未测试)
__m128i values = _mm_loadl_epi64((__m128i*)array);
__m128i order = _mm_set_epi8(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0, 1, 2, 3, 4, 5, 6, 7);
values = _mm_shuffle_epi8(values, order);
int result = _mm_movemask_epi8(_mm_slli_epi32(values, 7));
此假设数组为字符数组。如果你不能做到这一点,它需要一些更多的载荷和包装,它变得有点讨厌。
This assumes the array is an array of chars. If you can't make that happen, it takes some more loads and packs and it becomes a bit annoying.
这篇关于8布尔转换为一个字节的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!