Rog Matthews
Rog Matthews

Reputation: 3247

Meaning of %04X in C and how to write the same in java

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.

Upvotes: 15

Views: 37396

Answers (4)

yonarp
yonarp

Reputation: 39

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)

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114807

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

Upvotes: 11

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27652

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.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409354

Lets break the format code "%04X" into its separate parts:

  • The X means that it will print an integer, in hexadecimal, large X for large hexadecimal letters
  • The 4 means the number will be printed left justified with at least four digits, print spaces if there is less than four digits
  • The 0 means that if there is less than four digits it will print leading zeroes.

Upvotes: 19

Related Questions