0

I'm trying to convert a signed int variable to a 3 byte array and backwards.

In the the function getColorint, I'm converting the int value to the byte array. That works fine!

    public byte [] getColorByte(int color1){
    byte[] color = new byte[3];
    color[2] = (byte) (color1 & 0xFF);
    color[1] = (byte) ((color1 >> 8) & 0xFF);
    color[0] = (byte) ((color1 >> 16) & 0xFF);
    return color;
    }

But if I try to convert the byte array back to the Integer with the getColorint function:

    public int getColorint(byte [] color){
    int answer = color [2];
    answer += color [1] << 8;
    answer += color [0] << 16;
    return answer;
    }

it only works for positive integer values.

Here is a screenshot during the debug: screenshot

My input int value is -16673281 but my output int value is 38143.

Can anyone help me?

Thanks :)

1

3 Answers 3

1

The Color class defines methods for creating and converting color ints. Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue. You should use it.

Sign up to request clarification or add additional context in comments.

Comments

1

The problem here is that byte is signed. When you do int answer = color[2] with color[2] == -1, then answer will be also -1, i.e. 0xffffffff, whereas you want it to be 255 (0xff). You can use Guava 's UnsignedBytes as a remedy, or simply take color[i] & 0xff which casts it to int.

Comments

0

As is Color represents in 4 bytes, you should store also an alpha channel.

From Int :

public byte [] getColorByte(int color1){
    byte[] color = new byte[4];
    for (int i = 0; i < 4; i++) {
        color [i] = (byte)(color1 >>> (i * 8));
    }
    return color;
}

To Int :

public int getColorInt(byte [] color){
    int res = ((color[0] & 0xff) << 24) | ((color[1] & 0xff) << 16) |
          ((color[2] & 0xff) << 8)  | (color[3] & 0xff);
    return res;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.