Find the answer to your Linux question:
Results 1 to 3 of 3
Debian Release 5.0.4 (lenny) Kernel Linux 2.6.26-2-686 gcc (Debian 4.3.2-1.1) 4.3.2 The format character "%02X" doesn't work when and only when the value of char is "0xFF"in the printf function. ...
  1. #1
    Just Joined!
    Join Date
    Jun 2008
    Posts
    5

    Question %02X doesn't work in printf (Debian 5)

    Debian Release 5.0.4 (lenny)
    Kernel Linux 2.6.26-2-686
    gcc (Debian 4.3.2-1.1) 4.3.2

    The format character "%02X" doesn't work when and only when the value of char is "0xFF"in the printf function.
    I got 8 Fs instead of 2 Fs.

    Here is an example:
    PROGRAM:

    int main (int argc, char *argv[])
    {
    char xc[3];
    char *p = xc;

    memset ( xc, 0, 3);
    xc[1] = 0xff;

    for ( p = xc; p < xc + 3; p++)
    printf ("%02X\n", *p);

    return 0;
    }

    RESULT:
    00
    FFFFFFFF
    00

    I don't know why. Who could tell me the reason of that?
    Thanks very much!

  2. #2
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Try %.02x instead - the dot is essential here. Read the printf man pages for more information about what the formatting strings REALLY do. In your case, it specifies a MINIMUM field width of 2 characters, zero padded. The char input is interpreted as an integer. The dot means you want 2 digits of PRECISION, so it will only print 2 characters of precision, giving you the results you expect.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

  3. #3
    Just Joined!
    Join Date
    Jun 2008
    Posts
    5
    Oh, I see!
    Thanks very much!

    The parameter was converted to int type first in the printf function.
    In the converting process, the C extend the char type into int by extending the sign bit.
    So, char is signed int type in fact by default.
    I changed the type into unsighed char, and it works very well now.

    Thanks for your explanation very much!

    C is really a wonderful programming language.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...