Thread: somthing funky

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    If you start to think in terms of functions AND pointers this could be proven easier:
    Code:
    #include <stddef.h>
    #include <stdint.h>
    
    // Both dest and src points to buffers with the same size.
    void xorblk( void *dest, const void *src, size_t blksize,
                 const void *key, size_t keysize )
    {
      uint8_t *d;
      const uint8_t *s, *de, *k, *ke;
    
      d = dest;
      s = src;
      de = dest + blksize;
      k = key;
      ke = key + keysize;
    
      while ( d < de )
      {
        *d++ = *s++ ^ *k++;
        if ( k == ke ) k = key;
      }  
    }
    
    // test.
    #include <stdio.h>
    #include <string.h>
    
    static void display( const char *, const void *, size_t );
    
    int main( void )
    {
      char dest[32];    // with enough space to hold "encoded" data.
      char src[] = "TOMORROW NEVER DIES";
      const char key[] = "hel";
      size_t size, ksize;
    
      size = strlen( src );   // or (sizeof src - 1)
      ksize = strlen( key );  // or (sizeof key - 1)
    
      xorblk( dest, src, size, key, ksize );
      display( "original :", src, size );
      display( "encoded :", dest, size );
    
      xorblk( src, dest, size, key, ksize );
      display( "decoded :", src, size );
    }
    
    void display( const char *prompt, const void *p, size_t size )
    {
      const uint8_t *q, *qe;
      ptrdiff_t offset;
    
      fputs( prompt, stdout );
    
      q = p;
      qe = p + size;
    
      while ( q < qe )
      {
        offset = q - (const uint8_t *)p;
        if ( offset % 16 == 0 )
          printf( "\n%08tx:", offset );
    
        printf( " %02x", *q );
        q++;
      }
      putchar( '\n' );    
    }
    Code:
    $ ./xorenc
    original:
    00000000: 54 4f 4d 4f 52 52 4f 57 20 4e 45 56 45 52 20 44
    00000010: 49 45 53
    encoded :
    00000000: 3c 2a 21 27 37 3e 27 32 4c 26 20 3a 2d 37 4c 2c
    00000010: 2c 29 3b
    decoded :
    00000000: 54 4f 4d 4f 52 52 4f 57 20 4e 45 56 45 52 20 44
    00000010: 49 45 53
    Last edited by flp1969; 06-06-2023 at 05:49 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Funky output
    By zeldac in forum C Programming
    Replies: 15
    Last Post: 09-17-2014, 11:53 AM
  2. Somthing weired with C !!
    By wasem21 in forum C Programming
    Replies: 9
    Last Post: 12-18-2010, 12:02 PM
  3. XP allowing me to do somthing 2K won't! Wow
    By Queatrix in forum Windows Programming
    Replies: 0
    Last Post: 07-25-2007, 04:52 PM
  4. Funky enum
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 07-21-2006, 10:33 AM
  5. funky new avatar
    By iain in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 01-14-2002, 11:44 AM

Tags for this Thread