从32位数字中提取字节

问题描述 投票:3回答:1

这并不重要,应该很简单,我只是不明白我在做什么错。其背后的故事是我正在attiny85上使用tinyNeoPixel lib,并且我尝试的潜水深度超出了我的需要。

这是传统的ANSI C,我正在使用Raspberry Pi3进行此测试,但是在这种情况下,这应该无关紧要。按预期,printf上的sizeof(c)仅显示'c'为4个字节。

我正在尝试提取存储为32位数字的颜色的红色,绿色和蓝色部分

显然,我无法以1字节的值返回结果,请问我该怎么做?仅强制转换为(uint8_t)会产生零。

谢谢。

pi3:~/src$ cat a.c
#include <stdio.h>

typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;

#define Red(x)   (x & 0xff000000)
#define Green(x) (x & 0x00ff0000)
#define Blue(x)  (x & 0x0000ff00)

void main()
{
    uint32_t c;
    uint8_t r,g,b;

    c=0xffeecc00;
    r=Red(c);
    g=Green(c);
    b=Blue(c);

    printf("%d - %08x - %02x %02x %02x\n", sizeof(c), c, r, g, b);
    printf("%d - %08x - %02x %02x %02x\n", sizeof(c), c, Red(c), Green(c), Blue(c));
}


pi3:~/src$ gcc a.c -o a
pi3:~/src$ ./a
4 - ffeecc00 - 00 00 00
4 - ffeecc00 - ff000000 ee0000 cc00

解决方案是:

#define Red(x) (((x) & 0xff000000) >> 24)
#define Green(x) (((x) & 0xff000000) >> 16)
#define Blue(x) (((x) & 0xff000000) >> 8)
c casting bitmask
1个回答
2
投票

您需要移动以及遮罩。也就是说,尝试类似

#define Red(x) (((x) & 0xff000000) >> 24)

并且同样适用于Green()Blue()宏。

((还请注意,为安全起见,我在宏定义中添加了两对额外的括号。)

© www.soinside.com 2019 - 2024. All rights reserved.