Allan Macmillan
Allan Macmillan

Reputation: 1491

Java - Integer to 4 character Hex

How Can I convert an integer into a 4 character hex number. I need the extra padding of 0s if it isnt long enough.

So 2 -> 0x0002, 18 -> 0x0012 etc

I am using Java

Upvotes: 0

Views: 1452

Answers (2)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

public static String toPaddedHex(int i) {
    return String.format("0x%04X", i);
}

Example:

System.out.println(toPaddedHex(123));

Prints:

0x007B

Upvotes: 0

Pshemo
Pshemo

Reputation: 124235

How about String.format("%04X", decInt);?

If you want to add 0x part just place it at start of pattern used in this method like String.format("0x%04X", decInt);

Upvotes: 5

Related Questions