十六进制颜色代码到RGB数字

时间:2016-02-05 01:47:07

标签: c

我无法弄清楚如何做到这一点。我有一个带有颜色名称或十六进制代码(#ffffff)的字符数组,它没有将正确的RGB值返回给main,也没有超过"#"读取6个十六进制数字。我真的生锈了,大约一年没有编码,所以请批评你看到的任何东西。

/**readColor()
Converts the decimal values, color name or hex value read from
the input stream to the 3 byte RGB field

Returns the rgb values if successful.  On error prints errmsg and
exits.
**/
color_t readColor(FILE *infile, char *errmsg) 
{
int rc, red, green, blue;
char alpha[7] = {};
int i=0;

rc = fscanf(infile, "%d %d %d\n", &red, &green, &blue);
if(rc == 3){
    if(red>=0 && red<=255 && green>=0 && green<=255 && blue>=0 && blue<=255){
        return((color_t){red, green, blue});
    }

}
if (rc != 0){
    printf("%s", errmsg);
    return((color_t){0,0,0});
}


fgets(alpha, 10, infile);
fputs(alpha);

i=0;
if(strcmp(alpha, "white")==0){
    return((color_t){255, 255, 255 });
}
else if(strcmp(alpha, "red")==0){
    return((color_t){255, 0, 0});
}
else if(strcmp(alpha, "blue")==0){
    return((color_t){0, 0, 255});
}
else if(strcmp(alpha, "purple")==0){
    return((color_t){128, 0, 255});
}
else if(strcmp(alpha, "black")==0){
    return((color_t){0, 0, 0});
}
else if(strcmp(alpha, "green")==0){
    return((color_t){0, 255, 0});
}
else if(strcmp(alpha, "orange")==0){
    return((color_t){255, 128, 0});
}
else if(strcmp(alpha, "yellow")==0){
    return((color_t){255, 255, 0});
}
else if(alpha[0] == "#"){
    alpha++;
    if(sscanf(alpha, "%2x%2x%2x", &red, &green, &blue)!= 3){
        printf("%s", errmsg);
    }
    else{
        return((color_t){red, green, blue});
    }
}
else{
    printf("%s", errmsg);
}

return((color_t){0, 0, 0});
}

2 个答案:

答案 0 :(得分:1)

您可以使用%x格式说明符来读取十六进制值。 0填充宽度为2,无需进行范围测试。 e.g。

int r, g, b;
if( 3 == scanf( "#%02x%02x%02x", &r, &g, &b ) )
{
    printf( "Red   : %3d (%02x)\n", r, r );
    printf( "Green : %3d (%02x)\n", g, g );
    printf( "Blue  : %3d (%02x)\n", b, b );
}

答案 1 :(得分:0)

alpha[0] == "#"
            ^ ^
            double quotes for string literal

应该是

alpha[0] == '#'
            ^ ^
            single quotes for character literal

将单个字符与字符串文字进行比较是违反约束(感谢@AnT指出术语错误),编译器不应允许它。而是将单个字符与字符文字进行比较。