Last active
September 30, 2015 10:02
-
-
Save masterzorag/e6d8682cae5660abc757 to your computer and use it in GitHub Desktop.
C binary AND, OR operators play with 32bit int
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gcc -o demo main.c -Wall | |
#include <stdio.h> | |
typedef unsigned int uint32_t; | |
/* | |
ddacacba | |
&: 00ACACBA | |
|: DDFFFFFF | |
*/ | |
static uint32_t mix_color(const uint32_t bg, const uint32_t fg) | |
{ | |
uint32_t a = fg >>24; | |
if(a == 0) return bg; | |
uint32_t rb = (((fg & 0x00FF00FF) * a) + ((bg & 0x00FF00FF) * (255 - a))) & 0xFF00FF00; | |
uint32_t g = (((fg & 0x0000FF00) * a) + ((bg & 0x0000FF00) * (255 - a))) & 0x00FF0000; | |
uint32_t Fg = a + ((bg >>24) * (255 - a) / 255); | |
return (Fg <<24) | ((rb | g) >>8); | |
} | |
int main() | |
{ | |
while(1) | |
{ | |
uint32_t color = 0; | |
fscanf(stdin, "%8x", &color); // 11223344 | |
printf(" : %.8X\n", color <<24); // 44000000 | |
printf(" : %.8X\n", color <<24 | (color & 0x00FFFFFF)); // 44223344 | |
// 44000000 | 00223344 = 44223344 | |
//0xAARRGGBB | |
printf("&: %.8X\n", color & 0x00FFFFFF); // goes A to 00, rest untouched | |
printf("|: %.8X\n", color | 0x00FFFFFF); // leave A untouched, RGB to FF | |
unsigned char i, *p = (unsigned char*)&color; | |
for(i = 0; i < 4; i++) | |
{ | |
printf("%d: %.2x %p \n", i, *p, p); | |
p++; | |
} puts(""); | |
/* | |
00998877 on LE have: | |
0: 77 0x7ffeae5d2a14 | |
1: 88 0x7ffeae5d2a15 | |
2: 99 0x7ffeae5d2a16 | |
3: 00 0x7ffeae5d2a17 | |
*/ | |
printf("m: %.8X\n", mix_color(0x00000000, color)); | |
puts(""); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
./demo
00998877
: 77000000
: 77998877
&: 00998877
|: 00FFFFFF
0: 77 0x7ffeae5d2a14
1: 88 0x7ffeae5d2a15
2: 99 0x7ffeae5d2a16
3: 00 0x7ffeae5d2a17
m: 00000000
11998877
: 77000000
: 77998877
&: 00998877
|: 11FFFFFF
0: 77 0x7ffeae5d2a14
1: 88 0x7ffeae5d2a15
2: 99 0x7ffeae5d2a16
3: 11 0x7ffeae5d2a17
m: 110A0907