Mapping color representations

exercise No. 256

Q:

A developer requires RGB based colors. Thus a color will be represented by its red, green and blue components each ranging from 0 to 255. As an example (255, 0, 100) denotes a full red intensity, zero green and medium blue.

Our developer maps this range [0, 255] to a Java byte's range [-128, 127]. The given example will thus read (127, -128, -28).

Our developer wants to map triples like the former (127, -128, -28) back and forth into a no longer used attribute of type int:

/**
 * Pack color components (r, g, b) ranging from -128 to 127 into
 * an <code>int</code>. Inverse operation to {@link #int2rgb(int)}.
 *
 * @param r Red component ranging from 128 to 127
 * @param g Green component ranging from 128 to 127
 * @param b Blue component ranging from 128 to 127
 * @return Ein der Farbe eindeutig entsprechender int Wert.
 */
static public int rgb2int(final byte r, final byte g, final byte b) {
    ...// Implementation irrelevant with respect to given task
  return ...;
}

/**
 * Convert an <code>int</code> color specification back into its three (r, g, b) components.
 * Inverse operation to {@link #rgb2int(byte, byte, byte)}.
 *
 * @param color A color value combining an (r, g, b) triple.
 * @return An array of length 3 representing (r, g, b) values.
 */
static public byte[] int2rgb(final int color) {
   ...// // Implementation irrelevant with respect to given task
  return new byte[]{..., ..., ...};
}

Is this possible? Explain your statement.

Tip

Consider the underlying data types.

A:

An int consisting of four bytes can easily accommodate three byte values.