petrov
petrov

Reputation: 1155

RGB color system as a data type

An RGB color system can represent 256 different colors by combining different shades of red, green and blue. Each shade can be represented as a number. Define a C type to represent the RGB state.

From my understanding this would be a proper C type, not sure if I am correct though:

struct{
    int R[256];
    int G[256];
    int B[256];
} color;

Would that be correct or is there a more proper / more efficient way of doing this?

Upvotes: 1

Views: 19389

Answers (4)

MattG
MattG

Reputation: 1426

The array fields are unnecessary. A single int can hold values from 0 to 255 and is thus adequate for representing each of the shades. However, uint8_t is smaller and conveys the desired range of values explicitly:

#include <stdint.h> //Contains uint8_t
typedef struct color {
    uint8_t R;
    uint8_t G;
    uint8_t B;
} color_t;

color_t very_red;
very_red.R = 255U;
very_red.G = 0U;
very_red.B = 0U;

Note how typedef lets you subsequently reference color_t rather than having to write struct color.

Upvotes: 1

OnWhenReady
OnWhenReady

Reputation: 949

This is wrong. Remove the array and you move color right after struct. You try (with wrong syntax) to create a color struct with R,G and B arrays of size 256 (256 int values each). struct Color{ int R, int G, int B };

By the way: You only need 8bits to address 256 states of R,G,B. So uint8_t (unsigned char) will be a better candidate in comparison to int.

Upvotes: 0

Biduleohm
Biduleohm

Reputation: 752

One int is 4 bytes so with 3 int you take 12 bytes.

If you use 3 unsigned char (which take only 1 byte each) you can save 75% of space (if we don't count the eventual padding).

And there is no need for array here.

Also this statement is false: "can represent 256 different colors" it's 256 * 256 * 256 colors...

Upvotes: 0

Jongware
Jongware

Reputation: 22457

All you need is a structure that can hold three values, each in the range 0..255. Your proposed structure holds 3*256 * sizeof(int) = 768 * sizeof(int), way too much. Use this instead:

struct color {
    unsigned char R;
    unsigned char G;
    unsigned char B;
};

Note the correct placement of the struct identifier color.

You would use this structure further on in your program like this:

struct color bright_orange;

bright_orange.R = 255;
bright_orange.G = 128;
bright_orange.B = 0;

Upvotes: 3

Related Questions