3

i have a simple byte array that i want to take colours from. My plan was to have three bits from red, three bits for green, and two bits for blue. 8-bit.

I think the colours are right:

Please correct me if i'm wrong,

 byte[] colours = new byte[256]; //256 different colours, 8 * 8 * 4 
                                 //(3 bits(red) + 3 bits(green) + 2 bits(blue)
 int index = 0;
 for(byte r = 0; r < 8; r++){ 
    for(byte g = 0; g < 8; g++){
       for(byte b = 0; b < 4; b++){
           byte rr = (r & 255);
           byte gg = (g & 255);
           byte bb = (b & 255);
           colours[index++] = (rr << 5 | gg << 2 | bb);   
       }
   }
}

My goal is to make a getColor(byte r, byte g, byte b) like

public static byte getColor(byte r, byte g, byte b){
    return colours[return the right color using r g b];
}

But i don't know how. Here's where i need help.

I would like to rather not use the Color class if it's possible.

Other information: I'm using a BufferedImage.TYPE.BYTE.INDEXED to paint on.

Sorry if my english is bad :)

EDIT Fixed where it was wrong

thetheodor
  • 248
  • 2
  • 22

1 Answers1

0

Java's byte is signed, represented in 2's complement, so you can't just shift that way.
From 128 on, you have to reverse the bit pattern, using negative values.

byte[] colours = new byte[256];

for(int i = 0; i < colours.length; i++){ 
    colours[i] = (byte) (i < 128 ? i : i - 256);
}

Your method should be something along the lines of:

public static byte getColour(byte r, byte g, byte b)
        throws InvalidColourException {
    if (r >= 8 || r < 0)
        throw new InvalidColourException("Red is out of range.");
    if (g >= 8 || g < 0)
        throw new InvalidColourException("Green is out of range.");
    if (b >= 4 || b < 0)
        throw new InvalidColourException("Blue is out of range.");
    int i = (int) r << 5;
    i += (int) g << 2;
    i += (int) b;
    return colours[i];
}

Although, you could shrink it all to a single method, and discard the array:

public static byte getColour(byte r, byte g, byte b)
        throws InvalidColourException {
    if (r >= 8 || r < 0)
        throw new InvalidColourException("Red is out of range.");
    if (g >= 8 || g < 0)
        throw new InvalidColourException("Green is out of range.");
    if (b >= 4 || b < 0)
        throw new InvalidColourException("Blue is out of range.");
    int c = (int) r << 5;
    c += (int) g << 2;
    c += (int) b;
    return (byte) c;
}
afsantos
  • 5,178
  • 4
  • 30
  • 54