In the java project i am working on, some portion of the project was written previously by someone else in C and now i need to write the same in Java.
There is a statement in C code for printing to a file:
fprintf(ff, "%04X ", image[y*width+x]);
Firstly i am not sure about the meaning of %04X
. I think it means that if image[i]
has length five or more then print only leftmost four chararacters. To do the same in Java i thought about masking the value using and
operation
image[i] & 0xFFFF
Can someone please tell me the correct meaning of %04X
and how to do the same in Java? Thanks.
Lets break the format code "%04X"
into its separate parts:
X
means that it will print an integer, in hexadecimal, large X
for large hexadecimal letters4
means the number will be printed left justified with at least four digits, print spaces if there is less than four digits0
means that if there is less than four digits it will print leading zeroes.Understand by Examples
printf ("%d", 75); // Output -> '75' (Decimal Number)
printf ("%X", 75); // Output -> '4B' (X for large hexadecimal letters)
printf ("%4X", 75); // Output -> ' 4B' (Left justified with 4 spaces)
printf ("%04X", 75); // Output -> '004B' (Left justified with 0 until 4 digits)
The value is formatted as a hexadecimal integer with four digits and leading zeros. Java uses the same format string syntax. You can find it in the javaDoc of Formatter
.
Excerpt:
'x', 'X' integral The result is formatted as a hexadecimal integer
A related functions are
// create a String with the formatted value.
String formatted = String.format("%04X ", image[y*width+x]);
// write a formatted value to the console (*)
System.out.printf("%04X ", image[y*width+x]);
(*) - write it to the PrintStream
System.out
which is usually the console but can be redirected to a file or something else
The X in %04X means hexadecimal, with ABCDEF instead of abcdef, and the 04 means print at least four digits, padding with leading zeros. It will use more digits if needed.
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