Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format() and hex numbers in Java

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.

like image 968
Fitzoh Avatar asked Mar 07 '12 22:03

Fitzoh


People also ask

What is hex string format?

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.

What is hex string in Java?

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.

What is string format in Java?

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.

What is %d and %s in Java?

%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"


2 Answers

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);
like image 66
Daniel Martin Avatar answered Oct 20 '22 23:10

Daniel Martin


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.

like image 38
Bohemian Avatar answered Oct 20 '22 23:10

Bohemian