如何在c中进行位集/字节数组转换 [英] how to make a bit-set/byte-array conversion in c

查看:90
本文介绍了如何在c中进行位集/字节数组转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数组,
无符号字符q [32] = 1100111 ...

我如何生成一个4字节的位集 unsigned char p [4] ,使得该位集的位等于内部值数组,例如,第一字节p [0] = q [0] ... q [7];第二个字节p [1] = q [8] ... q [15],等等。

how can I generate a 4-bytes bit-set, unsigned char p[4], such that, the bit of this bit-set, equals to value inside the array, e.g., the first byte p[0]= "q[0] ... q[7]"; 2nd byte p[1]="q[8] ... q[15]", etc.

以及相反的操作方法,即给定位设置,生成数组?

and also how to do it in opposite, i.e., given bit-set, generate the array?

我自己的第一部分试用版。

my own trial out for the first part.

unsigned char p[4]={0};
for (int j=0; j<N; j++) 
{
    if (q[j] == '1')
    {
        p [j / 8] |= 1 << (7-(j % 8)); 
    }            
}

以上是正确的吗?有什么条件要检查吗?有什么更好的办法吗?

Is the above right? any conditions to check? Is there any better way?

编辑-1

我想知道上述方法是否有效?由于数组的大小可能高达4096甚至更大。

I wonder if above is efficient way? As the array size could be upto 4096 or even more.

推荐答案

我认为这不太可行。您正在将每个位与 1 进行比较,而实际上它应该是‘1’。您还可以通过除去 if 来使其效率更高:

I don't think that will quite work. You are comparing each "bit" to 1 when it should really be '1'. You can also make it a bit more efficient by getting rid of the if:

unsigned char p[4]={0};
for (int j=0; j<32; j++) 
{
    p [j / 8] |= (q[j] == `1`) << (7-(j % 8));           
}

反向操作也很简单。

unsigned char q[32]={0};
for (int j=0; j<32; j++) {
  q[j] = p[j / 8] & ( 1 << (7-(j % 8)) ) + '0';
}

您会注意到(布尔值)+'0'在1/0和'1'/'0'之间转换。

You'll notice the creative use of (boolean) + '0' to convert between 1/0 and '1'/'0'.

这篇关于如何在c中进行位集/字节数组转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆