简体   繁体   中英

Convert Integer to Hex String

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.

您可以在JDK中调用该方法。

String result = Integer.toHexString(131);

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM