Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c

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.

like image 612
Rog Matthews Avatar asked Mar 28 '12 06:03

Rog Matthews


4 Answers

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.
like image 142
Some programmer dude Avatar answered Oct 29 '22 14:10

Some programmer dude


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)
like image 24
yonarp Avatar answered Oct 29 '22 14:10

yonarp


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

like image 34
Andreas Dolk Avatar answered Oct 29 '22 13:10

Andreas Dolk


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.

like image 43
Thomas Padron-McCarthy Avatar answered Oct 29 '22 12:10

Thomas Padron-McCarthy