【问题标题】:How to shift a byte through multiple byte array如何通过多字节数组移动一个字节
【发布时间】:2019-04-16 22:43:58
【问题描述】:

我正在研究包含 15 层的 LED 塔,其中每一层包含 4 个字节(32 个 LED)。我希望能够从右向左移动一个字节。但是,多字节存在问题,无法弄清楚如何连续转换移位。

附加信息:

void Invert_Display(void){
for (int y = 0; y < LAYERS; y++){
    for (int x = 0; x < BYTES; x++){
        LED_Buffer[y][x] ^= (0b11111111);
    }
}
Update_Display();

其中UpdateDisplay函数如下:

void Update_Display(void){

    while(!TRMT);           // Wait until transmission register is empty

    for (int y = 0; y < LAYERS; y++){
        for (int x = 0; x < BYTES; x++){
        TXREG = LED_Buffer[y][x];
        while (!TRMT);
        }
    }

    LE = 1;                 // Data is loaded to the Output latch
    NOP();              
    LE = 0;                 // Data is latched into the Output latch

下面附上预期的结果。

【问题讨论】:

  • 1 位或 8 位移位多长时间?
  • 理想情况下,我想在每层中移动所有字节(所有 LED)。
  • 你能把你的 4 个字节打包成一个大的uint32_t 吗?如果是,那么您只需执行 1 位左移:my_uint32_variable &lt;&lt;= 1; — 或 my_uint32_variable *= 2;
  • 我必须指定使用哪个 LED_Buffer[y][x] 将值移入。假设我想从 LED_Buffer[0][0] 开始移动 0xAA 值并在 LED_Buffer 之外完成[0][3],所以它扫过整个显示器。那是我的最终目标。 * 我添加了一些代码来更好地了解它是如何完成的。我正在使用 PIC16F1829 微控制器来开发这个。
  • 我想主要问题是我使用字节更新显示,而移位通常是按单个位完成的,对吗?

标签: c byte bit-shift


【解决方案1】:

以下代码将向左移动一个字节数组。要移位的位数必须在 1 到 7 之间。移位超过 7 位需要额外的代码。

void shiftArrayLeft(unsigned char array[], int length, int shift) // 1 <= shift <= 7
{
    unsigned char carry = 0;                        // no carry into the first byte
    for (int i = length-1; i >= 0; i--)
    {
        unsigned char temp = array[i];              // save the value
        array[i] = (array[i] << shift) | carry;     // update the array element
        carry = temp >> (8 - shift);                // compute the new carry
    }
}

它通过存储数组中的旧值来工作。然后通过移动它并与前一个字节进行逻辑或进位来更新当前数组元素。然后计算新的进位(原始值的高位)。

函数可以用这样的代码调用

unsigned char array[] = { 0x00, 0x00, 0x00, 0xAA };
int length = sizeof(array) / sizeof(array[0]);
shiftArrayLeft(array, length, 1);

这会将数组更改为{ 0x00, 0x00, 0x01, 0x54 }

【讨论】:

  • 感谢您的回答!但是,我正在使用二维数组。更具体地说,代码中使用了 LED_Buffer[y][x]。理想的“y”参数只是告诉我正在使用哪一层。我尝试修改代码,但出现了error: (202) only lvalues can be assigned to or modified
  • @RytisBe 给定一个声明为unsigned char buffer[ROWS][COLS]的二维数组,您可以使用for (int i = 0; i &lt; ROWS; i++) shiftArrayLeft(buffer[i], COLS, 1);移动每一行
  • 好的,我明白了。但是,很难修改代码以允许整个 4 字节数组移动 32 位。
  • @RytisBe 我不确定你的意思。一次全部移位 32,还是一次移位 32 位?
  • 一次 1 位。我想把它扫过我正在驾驶的整个 32 个 LED。
猜你喜欢
  • 1970-01-01
  • 2021-11-30
  • 2023-03-15
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 2016-11-15
  • 2015-06-09
相关资源
最近更新 更多