【问题标题】:Is there a modality to modify the elements of a vector/array bit by bit?是否有一种方式可以逐位修改向量/数组的元素?
【发布时间】:2019-05-25 10:25:04
【问题描述】:

我正在设置一个 RamBlock“模拟”。使用需要逐位单独修改的十六进制静态布尔数组(10 个元素)。

uint8_t boolArray[10] = {0x03, 0xED, 0xE8, 0x00, 0xFF, 0x56, 0x01, 0x02, 0xAB, 0x18};

编辑:在需求字段中,它被赋予了一个原型函数:

Std_ReturnType _WriteBoolean(uint8_t ramBlockAddr, uint16_t ramBlockLength, uint16_t byteIndex, uint8_t bitIndex, const uint8_t* value, uint8_t length)

并且我可以使用参数修改以下内容:byteIndex、bitIndex、长度和值。

函数如下所示:

returnValue = _WriteBoolean((uint8_t*)&boolArray[0], 10, 0, 3, (uint8_t*) &x, 4);
/*Bits should be written with the value provided by "x"*/

我可以通过&boolArray[i] 访问 boolArray[] 的元素。不知道如何使用从函数(returnValue)获取的新布尔值修改/更新它。

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 使用按位运算。如果您想设置一点,请执行boolArray[position] |= (1 << bit - 1)。如果你想稍微改成 0,那么boolArray[position] &= ~(1 << bit - 1)。你也可以有一个联合数组。
  • @VioAriton 我想到了,我会试试的,无论如何我将每个单独的元素定义为“#define BIT1 0x03”......并将数组初始化为“uint8_t boolArray[10] = {BIT1 ...}。我是不是想多了?谢谢!
  • 你可以随心所欲,只要它有效。没有最好的办法。另一种方法是使用联合,例如 this
  • 忘了,需求页面上有一个原型函数:_writeBoolean(uint8_t ramBlockAddr, uint16_t ramBlockLength, uint16_t byteIndex, uint8_t bitIndex, const uint8_t* value, uint8_t length)。我还可以使用它来修改字节流中的位,选择从哪里开始、要更新的长度等,如下所示:_writeBoolean((uint8_t*)&boolArray[0], 10, 0, 3, (uint8_t*) &x, 4);
  • 另外,假设我想将函数中的值存储在一个变量中,然后每次进行更改时更新数组,我不能因为数组的值是使用定义的宏,对吧?

标签: c memory


【解决方案1】:

要打开和关闭某些位,可以使用按位运算。例如,如果我们有值0x3,即二进制的 0011,要打开第三位,我们可以使用value |= (1 << 2)。我们将临时常量1 的内容向前移动两个位置,然后我们执行OR 的值:0011 | 0100 = 0111。

要关闭一点,我们做同样的事情,只是我们取常数的补码,然后我们执行 AND 的值:value &= ~(1 << 2) => 0111 & ~0100 => @ 987654329@ & 1011 => 0011

联合也可以用来表示一块内存:

typedef union {

    uint_8 data;

    struct {

      uint8_t cell1;
      uint8_t cell2;
      uint8_t cell3;
      uint8_t cell4;
      uint8_t cell5;
      uint8_t cell6;
      uint8_t cell7;
      uint8_t cell8;

   };

} Block_t

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多