【问题标题】:Storing 0s and 1s in an array in a 32-bit integer and performing bit operation以 32 位整数将 0 和 1 存储在数组中并执行位运算
【发布时间】:2013-11-30 02:26:44
【问题描述】:

我有一个大小为 32 的数组。数组中的每个元素都是 0 或 1。我希望能够将它们存储到 32 位整数的位位置,并对其执行按位运算。我该怎么做?

另外,如果我有两个大小为 32 的数组,并且我想一次对具有相同索引的元素进行按位运算,我可以这样做吗?

op_and[31:0] = ip_1[31:0] & ip_2 [31:0];

我正在使用 gcc 编译器。

【问题讨论】:

标签: c++ bit-manipulation


【解决方案1】:

您可以使用 or 运算符 |和位移( > )。

uint32_t myInt = 0;
for( int index=0; index < 32; index++ )
{
  myInt |= ( arrayOf32Ints[i] << i );
}

根据您的问题,此示例假定 arrayOf32Ints 的值为 0 或 1。 如果它们可能包含“任何真”或假值,则应明确要求(有些人会告诉您使用 !! 但标准不保证真为 1)。

那么这条线就是

myInt |= ( (arrayOf32Ints[i])?1:0) << i );

如果您想打开或关闭单个位,您可以这样做:

myInt |= (1<<3); //Sets bit 3 true by shifting 1 3 bits up (1 becomes 4), and ANDing it with myInt.
myInt |= 4; // Sets bit 3 by ANDing 4 (The binary form of 4 is 100) with myInt.
myInt ^= (1<<5);; // Turns OFF bit 5 by XORing it with myInt (XOR basically means "Any bits which are not the same in both numbers")
myInt ^= 16; //Sets bit 5 by XORing it with myInt (16 is 10000 in binary)

【讨论】:

  • 谢谢。有没有办法直接为各个位分配值?假设我希望上面 myInt 变量的第 3 位存储 1。这可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
相关资源
最近更新 更多