Reputation: 9986
i have an Integer value and i want to convert it on Hex.
i do this:
private short getCouleur(Integer couleur, HSSFWorkbook classeur) {
if (null == couleur) {
return WHITE.index;
} else {
HSSFPalette palette = classeur.getCustomPalette();
String hexa = Integer.toHexString(couleur);
byte r = Integer.valueOf(hexa.substring(0, 2), 16).byteValue();
byte g = Integer.valueOf(hexa.substring(2, 4), 16).byteValue();
byte b = Integer.valueOf(hexa.substring(4, 6), 16).byteValue();
palette.setColorAtIndex((short) 65, r, g, b);
return (short) 65;
}
}
In output i have this:
couleur: 65331
Hexa: FF33
hexa.substring(0, 2): FF
hexa.substring(2, 4): 33
hexa.substring(4, 6):
r: -1
g: 51
b: error message
error message: String index out of range: 6
Thx.
Upvotes: 1
Views: 7037
Reputation: 8896
If I understand correctly you want to split an int
into three bytes (R, G, B).
If so, then you can do this by simply shifting the bits in the integer:
byte r = (byte)((couleur >> 16) & 0x000000ff);
byte g = (byte)((couleur >> 8) & 0x000000ff);
byte b = (byte)(couleur & 0x000000ff);
That's much more efficient. You don't have to do it through conversion to String
.
Upvotes: 4
Reputation: 61
you can call the method in JDK.
String result = Integer.toHexString(131);
Upvotes: 6
Reputation: 44824
The problem is that you are assuming that the hex string will be six digits long.
try String.format ("%06d", Integer.toHexString(couleur));
to pad it with zeros if less than 6 digits longs
Upvotes: 2