Thread: printing hex

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    205

    printing hex

    Hi,
    I have a weird problem when printing hex values.
    Code:
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <sys/mman.h> /* mmap() is defined in this header */
    #include <fcntl.h>
    #include <stdio.h>
    
    int main (int argc, char *argv[])
    {
     int fdin, fdout;
     char *src, *dst;
     struct stat statbuf;
    
     if (argc != 3) {
       printf("usage: a.out <fromfile> <tofile>");
       exit(1);
     }
    
     /* open the input file */
     if ((fdin = open (argv[1], O_RDONLY)) < 0)
       printf("can't open %s for reading", argv[1]);
    
     /* open/create the output file */
     if ((fdout = open (argv[2], O_RDWR | O_CREAT | O_TRUNC)) <
    0)
       printf("can't create %s for writing", argv[2]);
    
     /* find size of input file */
     if (fstat (fdin,&statbuf) < 0)
       printf("fstat error");
    
    /* go to the location corresponding to the last byte */
     if (lseek (fdout, statbuf.st_size - 1, SEEK_SET) == -1)
       printf("lseek error");
    
     /* write a dummy byte at the last location */
     if (write (fdout, "a", 1) != 1)
       printf("write error");
    
    /* mmap the input file */
     if ((src =(char *) mmap (0, statbuf.st_size, PROT_READ, MAP_SHARED,
    fdin, 0)) == MAP_FAILED)
       printf("mmap error for input");
    
    
     /* mmap the output file */
     if ((dst =(char *) mmap (0, statbuf.st_size, PROT_READ |
    PROT_WRITE,MAP_SHARED, fdout, 0)) == MAP_FAILED)
       printf("mmap error for output");
    
    printf("Data: %x\n",src[0]);
     /* this copies the input file to the output file */
     memcpy(dst, src, statbuf.st_size);
    
    }
    The file that I use is a binary file containing the following:
    39 8e e3 38 8e 03 67 c0 c7 71 1c c7 71 1c 68

    when I do the printf at the end, I get Data: 38e38e39

    I would like it to print only 39 though and not the rest. Any idea how to do that. Thanks
    Amish

  2. #2
    Dump Truck Internet valis's Avatar
    Join Date
    Jul 2005
    Posts
    357
    Will simply masking off the other bytes suffice? src[0] & 0x000000ff

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    205
    Sweet that does the trick. Thanks a lot,
    Amish

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Printing integers in hex
    By skapykat in forum C Programming
    Replies: 5
    Last Post: 10-06-2008, 02:05 PM
  2. Replies: 11
    Last Post: 03-24-2006, 11:26 AM
  3. Printing Hex Value of a char
    By earth_angel in forum C Programming
    Replies: 6
    Last Post: 05-25-2005, 10:49 AM
  4. Printing numbers in hex format
    By miclus in forum C++ Programming
    Replies: 7
    Last Post: 01-29-2005, 07:04 AM
  5. Printing Hex as Binary
    By Mystic_Skies in forum C Programming
    Replies: 6
    Last Post: 11-22-2004, 04:18 PM