Thread: 4 char's from one int. . .

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    16

    4 char's from one int. . .

    Say I have an unsigned int x = 0x4F726E67, and I want to print the character values of that int( 0x4F, 0x72, 0x6E, 0x67 ) becomes ( 'O', 'r', 'n', 'g' ) either to stdout or to a file. There must be an easy way of doing this but it has eluded me. Any hints would be appreciated.

    Example of an attempt using strtol:
    Code:
    	for( i=0; i<length/4; i++ ) {
    		fread( &c, 4, 1, in );
    		
    	       	c = c ^ 0x54694772;
    		printf("c = &#37;d = 0x%x\n", c, c );
    		unsigned int foo = strtol( c, NULL, 2 );
    	fwrite( &foo, 1, 1, out );
    	}
    		
    	
    	fclose( in );	// Closes input file
    	fclose( out );	// Closes output file
    	return 0;
    }
    Last edited by k2712; 09-16-2007 at 12:10 PM.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    One possible method:
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main(void)
    {
       unsigned int value = 0x4F726E67;
       size_t i = sizeof value - 1;
       do {
          putchar(value >> CHAR_BIT * i);
       } while ( i-- > 0);
       return 0;
    }
    
    /* my output
    Orng
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    16
    Thank you Dave, that works perfectly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  2. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  3. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  4. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-02-2003, 12:26 AM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM