-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrgb2hex.c
79 lines (78 loc) · 1.56 KB
/
rgb2hex.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* this is an ugly fast program I wrote since I called a program called
'rgb2hex' in one of my old shell scripts but could not find the program
anywhere on my system. This re-implements it. */
int main(int argc, char **argv) {
char redc[4]="000";
char bluec[4]="000";
char greenc[4]="000";
if(argc != 2)
{
fprintf(stderr, "Error: I need one argument exactly, in format (R,G,B) with values\nfrom 0-255 for each.\n");
return 1;
}
int i=0;
int done=0;
int offset=0;
/* get red */
while((argv[1][offset+i]) != '\0' && i<3 && done != 1)
{
if(argv[1][offset+i] == ',')
{
redc[i]='\0';
done=1;
}
else
{
redc[i]=argv[1][offset+i];
}
i++;
}
offset += i;
done=0;
/*green*/
i=0;
while((argv[1][offset+i]) != '\0' && i<3 && done != 1)
{
if(argv[1][offset+i] == ',')
{
greenc[i]='\0';
done=1;
}
else
{
greenc[i]=argv[1][offset+i];
}
i++;
}
offset += i;
done=0;
i=0;
/* get blue */
while( i<3 && done != 1)
{
if(argv[1][offset+i] == ','||argv[1][offset+i] == '\0')
{
bluec[i]='\0';
done=1;
}
else
{
bluec[i]=argv[1][offset+i];
}
i++;
}
int red=atoi(redc);
int green=atoi(greenc);
int blue=atoi(bluec);
if(red > 255 || green > 255 || blue > 255)
{
fprintf(stderr,"E: I only work on 8 bit RGB values; sorry.\n");
return 2;
}
/* printf("%s %s %s\n",redc,greenc,bluec);*/
printf("%02X%02X%02X\n",red,green,blue);
return 0;
}