Created
February 10, 2016 22:11
-
-
Save obskyr/9d28918ee49bd49aad40 to your computer and use it in GitHub Desktop.
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
#include <stdint.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
// Parse dispmanx-safe colors from command-line arguments | |
typedef struct __attribute__((__packed__)) { | |
uint8_t r; | |
uint8_t g; | |
uint8_t b; | |
uint8_t x; | |
} rgbx_t; | |
rgbx_t parseColor(char* hexString) | |
{ | |
rgbx_t rgbx = {0, 0, 0, 0}; // Return black on error | |
uint8_t* colorPtr = (uint8_t*) &rgbx; | |
if (hexString[0] == '#') | |
{ | |
hexString += 1; | |
} | |
if (strncmp(hexString, "0x", 2) == 0) | |
{ | |
hexString += 2; | |
} | |
uint32_t colorInt = strtol(hexString, NULL, 16); | |
if (strlen(hexString) == 6) | |
{ | |
int i; | |
for (i = 2; i >= 0; i--) { | |
colorPtr[2 - i] = (uint8_t) (colorInt >> (i * 8)); | |
} | |
} | |
else if (strlen(hexString) == 3) | |
{ | |
int i; | |
for (i = 2; i >= 0; i--) { | |
colorPtr[2 - i] = (uint8_t) (colorInt >> (i * 4)) & 0xF; | |
colorPtr[2 - i] |= colorPtr[2 - i] << 4; | |
} | |
} | |
return rgbx; | |
} | |
int main(int argc, char** argv) { | |
char* hexString = "000000"; | |
char c; | |
while ((c = getopt(argc, argv, "b:")) != -1) | |
{ | |
switch (c) | |
{ | |
case 'b': | |
hexString = optarg; | |
break; | |
} | |
} | |
rgbx_t rgbx = parseColor(hexString); | |
printf("Colors (RGBX): %x %x %x %x\n", rgbx.r & 0xFF, rgbx.g & 0xFF, rgbx.b & 0xFF, rgbx.x & 0xFF); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment