将 uint_8 更改为 x 倍二进制 1 MSB
Change uint_8 to x times binary 1 MSB
我正在为我的学校项目编写一个 Max72xx 库,我找到了一种使用数据表附带的寄存器来设置列的方法。现在,我也找到了一种方法来设置它们的高度。所以我创建了一个带有两个参数的函数:row
,它基本上将 x 轴发送到芯片,以及设置 y 轴的高度。
我在这段代码中所做的基本上是以下内容:
- 用户设置了1到8之间的x轴(参数
const uint8_t& row
)
- 用户设置y轴在1到8之间(参数
uint8_t height
)
我想实现以下目标:
- 如果
height
设置为三:应创建以下位模式:1110 000
。或者,如果用户使用 8,我希望函数创建 1111 1111
。或者,如果用户将 5 设置为 y 轴,我希望函数创建 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 是最高像素。
现在这段代码像我之前描述的那样工作,但我认为有一种更简单、更有效的方法来解决这个问题。我想知道一些建议。提前致谢。
只有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
只需使用这个:
uint8_t pattern = (0xff00u >> height);
或者这样:
uint8_t pattern = (0xffu << (8 - height));
只要参数是 unsigned,就不用担心位移时溢出,行为是 well-defined.
我正在为我的学校项目编写一个 Max72xx 库,我找到了一种使用数据表附带的寄存器来设置列的方法。现在,我也找到了一种方法来设置它们的高度。所以我创建了一个带有两个参数的函数:row
,它基本上将 x 轴发送到芯片,以及设置 y 轴的高度。
我在这段代码中所做的基本上是以下内容:
- 用户设置了1到8之间的x轴(参数
const uint8_t& row
) - 用户设置y轴在1到8之间(参数
uint8_t height
)
我想实现以下目标:
- 如果
height
设置为三:应创建以下位模式:1110 000
。或者,如果用户使用 8,我希望函数创建1111 1111
。或者,如果用户将 5 设置为 y 轴,我希望函数创建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 是最高像素。 现在这段代码像我之前描述的那样工作,但我认为有一种更简单、更有效的方法来解决这个问题。我想知道一些建议。提前致谢。
只有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
只需使用这个:
uint8_t pattern = (0xff00u >> height);
或者这样:
uint8_t pattern = (0xffu << (8 - height));
只要参数是 unsigned,就不用担心位移时溢出,行为是 well-defined.