将uint_8更改为 x 乘以二进制 1 MSB

Change uint_8 to x times binary 1 MSB

本文关键字:二进制 MSB uint      更新时间:2023-10-16

我正在为我的学校项目编写一个Max72xx库,我找到了一种使用数据表附带的寄存器设置列的方法。现在,我还找到了一种设置它们高度的方法。所以我创建了一个包含两个参数的函数:row,基本上将 x 轴发送到芯片,以及设置 y 轴的高度。

我在此代码中所做的基本上如下:

  • 用户在 1 到 8 之间设置 x 轴(参数const uint8_t& row(
  • 用户在 1 到 8 之间设置 y 轴(参数uint8_t height(

我想实现以下目标:

  • 如果height设置为 3:应创建以下位模式:1110 000.或者,如果用户使用 8,我希望函数创建1111 1111.或者,如果用户将 5 设置为 y 轴,我希望 fucntin 创建1111 1000等的位模式。

我提供的代码如下(这段代码在函数 setColumn 中(:

if (height >= 1 && height <= 8) { // if the height is between the matrix range
uint8_t pattern = 0x00; // create a pattern to send to the chip
uint8_t counter = 0; // counter for counting the zeros to shift left later on
for (uint8_t i = 0; i < height - 1; i++) { // this loop is repeated height amount of times
pattern |= 0x01; // create 1s in the pattern
pattern <<= 0x01; // shift it 1 to the left
}
pattern |= 0x01; // OR the LSB bit of the pattern
for (uint8_t i = 7; i > 0; i--) { // count the leading 0 bits to shift them to the MSB position
if (!(pattern >> i) & 1)
counter++;
else break;
}
pattern <<= counter;

MSB 是显示器上的最低像素,LSB 是最高像素。 现在这段代码的工作方式与我之前描述的一样,但我认为有一种更简单、更有效的方法来解决这个问题。我想知道一些建议。提前谢谢。

只需使用这个:

uint8_t pattern = (0xff00u >> height);

或者这个:

uint8_t pattern = (0xffu << (8 - height));

不要害怕位移期间溢出,只要参数是无符号的,行为是明确定义的。

只有 8 种模式?我只想定义一个const数组:

```
static const uint8_t patterns[] = {
0x10000000,
0x11000000,
0x11100000,
0x11110000,
0x11111000,
0x11111100,
0x11111110,
0x11111111,
};
if (height >= 1 && height <=8)
return patterns[height - 1];
// raise an exception or so