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.
The format for coding a hexadecimal string constant is: X'yy...yy' The value yy represents any pair of hexadecimal digits. You can specify up to 256 pairs of hexadecimal digits.
Hex String – A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: “245FC” is a hexadecimal string. Byte Array – A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With