Problem with Apache poi excel color cells

I am using apache poi to write excel data.

String colour = "A2C465";
byte[] ret = new byte[3];
for(int i=0; i<3; i++){
    ret[i] = (byte)hexToInt(colour.charAt(i * 2), colour.charAt(i*2+1));
}

public int hexToInt(char a, char b){
        int x = a < 65 ? a-48 : a-55;
        int y = b < 65 ? b-48 : b-55;
        return x*16+y;
    }

After loop iteration, I get ret = {-94, -60,101}. But the actual RGB code is {162,196,101} (since the conversion from int to byte). Because of this, the color next as different in excel sheet can you help me with this?

+4
source share
2 answers

Axel Richter's comment has the answer you are looking for, if you need to convert bytes to int, you should use bitwise and avoid saving the character. The following example shows bytes as their signed value when converted to int.

    byte[] ret = DatatypeConverter.parseHexBinary("A2C465");
    for (byte b: ret) {
        int asInt = b & 0xFF;
        System.out.println(b + " vs " + asInt);
    }
0
source

If the return value is negative, just add 256!

-94 + 256 = 162

-60 + 256 = 196

101 101, -128 127.

0

All Articles