Fitzoh Fitzoh - 1 year ago 134
Java Question

String.format() and hex numbers in Java

I'm trying to figure out why

is behaving the way it does.

Context: Systems programming class, writing an assembler.

There is a 5 character hex field in the object file, which I am creating from a value.

Tried using:
String.format("%05X", decInt);

This works as intended for positive numbers
(11 ->
However it fails for negative numbers
(-1 ->
instead of

I suppose I could just take a substring of the last 5 characters, but I would still like to figure out why it behaves this way.

Answer Source

The width used in format is always a minimum width. In this case, instead of using sub string operations I would suggest:

  String.format("%05X", decInt & 0xFFFFF);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download