Arduino在uint32_t和无符号字符之间转换



我使用的是rainbowduino,它有一些方法将单个r g b值作为无符号字符,还有一些方法使用24位rgb颜色代码。

我想将r g b值转换为uint32_t类型的24位颜色代码(这样我的所有代码都只需要使用r g b的值。

有什么想法吗?

我已经尝试过uint32_tresult=r<lt;16+g<lt;8+b;r=100 g=200 b=0给出绿色,但r=0 g=200 b=0没有给出

Rb.setPixelXY(unsigned char x, unsigned char y, unsigned char colorR, unsigned char colorG, unsigned char colorB)
This sets the pixel(x,y)by specifying each channel(color) with 8bit number.
Rb.setPixelXY(unsigned char x, unsigned char y, unit32_t colorRGB) 
This sets the pixel(x,y)by specifying a 24bit RGB color code.

驱动程序代码为:

void Rainbowduino::setPixelXY(unsigned char x, unsigned char y, uint32_t colorRGB /*24-bit RGB Color*/)
{
    if(x > 7 || y > 7)
    {
     // Do nothing.
     // This check is used to avoid writing to out-of-bound pixels by graphics function. 
     // But this might slow down setting pixels (remove this check if fast disply is desired)
    }
    else
    {
    colorRGB = (colorRGB & 0x00FFFFFF);
    frameBuffer[0][x][y]=(colorRGB & 0x0000FF); //channel Blue
    colorRGB = (colorRGB >> 8);
    frameBuffer[1][x][y]=(colorRGB & 0x0000FF); //channel Green
    colorRGB = (colorRGB >> 8);
    frameBuffer[2][x][y]=(colorRGB & 0x0000FF); //channel Red
    }
}

所以我想类似于上面的:

uint8_t x,y,r,b,g;
uint32_t result = (r << 16) | (g << 8) | b;
Rb.setPixelXY(x, y, result); 

应该起作用。我认为上面可能需要括号,以确保正确的排序,因为"+"高于"<<"。也可能不会受伤,但"|"更好,因为它不会防止不希望的进位。

第页。S.记住当移位为无符号时,除非你想要算术移位而不是逻辑移位。在这一点上,我不喜欢轮班,因为他们经常一团糟,效率低下。相反,工会是简单而有效的。

union rgb {
  uint32_t word;
  uint8_t  byte[3];
  struct {
    uint8_t  blue;
    uint8_t  green;
    uint8_t  red;
  } color ;
}rgb ;
// one way to assign by discrete names.
rbg.color.blue = b;
rbg.color.green = g;
rbg.color.red = r;
//or assign using array
rgb.byte[0] = b;
rgb.byte[1] = g;
rgb.byte[2] = r;
// then interchangeably use the whole integer word when desired.
Rb.setPixelXY(x, y, rgb.word); 

不要干扰轮班记录。

实现这一点的一种方法是将位向左移动。。。

uint32_t result = r << 16 + g << 8 + b;

最新更新