0

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.

home
  • 12,169
  • 5
  • 42
  • 54
Mercer
  • 9,298
  • 27
  • 91
  • 154

3 Answers3

5

you can call the method in JDK.

String result = Integer.toHexString(131);
PoWen
  • 51
  • 2
4

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.

Adam Dyga
  • 8,056
  • 3
  • 24
  • 34
2

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

Scary Wombat
  • 41,782
  • 5
  • 32
  • 62