Samashki95 Samashki95 - 4 months ago 69x
Java Question

Converting from Int to Hex in Delphi and Java

I have to convert the following Delphi code to Java:

function IntToHex(DecimalValue: Integer; MinimumWidth: Integer): Ansistring;
AnsiStrings.FmtStr(Result, '%.*x', [DecimalValue, MinimumWidth]);

The IntToHex function converts a DecimalValue integer into a hexadecimal format string of at least MinimumWidth characters wide.

I've implemented it in Java as:

public static String intToHex(int value)
return Integer.toHexString(value);

Do I need in Java to indicate that the resulting string must contain at least the specified number of digits like in Delphi with parameter MinimumWidth?
Did I already with my Java function implemented the full functionality from the Delphi IntToHeX-function?


If I correctly understand your question, I think your solution should be to use String.format in Java If you want hex numbers in the string you can use

String myFormattedString = String.format("%x", mynumber);

You can specify the lenght prepending it to the x, as

String myFormattedString = String.format("%4x", mynumber);

Where of course mynumber is a int or any other kind of valid number. If you want to pad with zeros you should use

String myFormattedString = String.format("%04x", mynumber);

You can use capital X to have capital letters in the resulting String

To have more information on the format option you can take a look at the following URL:

Hope this can help