1

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.

4
  • 1
    already answered here - stackoverflow.com/questions/5258415/… Commented Nov 22, 2013 at 8:46
  • @radai it's not the same problem Commented Nov 22, 2013 at 8:50
  • @AlexeyOdintsov I already use Commented Nov 22, 2013 at 8:50
  • You must pad the hex string before extracting the byte arrays. Already answered here: stackoverflow.com/questions/5446863/… Commented Nov 22, 2013 at 8:52

3 Answers 3

6

you can call the method in JDK.

String result = Integer.toHexString(131);
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Type mismatch: cannot convert from int to byte
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

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.