61

I'm trying to figure out why String.format() 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 -> 0000B) However it fails for negative numbers (-1 -> FFFFFFFF instead of FFFFF)

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.

1
  • 5
    The problem is the width set by the format method, in this case 5, is the minimum width.
    – twain249
    Commented Mar 7, 2012 at 22:44

2 Answers 2

91

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);
0
16

Format width only works to create a minimum number of digits, and only has effect on leading zeroes.

Instead of substring, you could use a bit mask:

String.format("%05X", decInt & 0x0FFFFF)

By the way, 11 -> 0000B, not 0000A as claimed in your question.

1
  • 1
    Ok, that makes sense now. Also went back and modified the A->B, cheers
    – Fitzoh
    Commented Mar 7, 2012 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.