Friday, November 4, 2011

One’s Complement Operator in C programming

One’s Complement Operator

On taking one’s complement of a number, all 1’s present in the number are changed to 0’s and all 0’s are changed to 1’s. For example one’s complement of 1010 is 0101. Similarly, one’s complement of 1111 is 0000. Note that here when we talk of a number we are talking of binary equivalent of the number. Thus, one’s complement of 65 means one’s complement of 0000 0000 0100 0001, which is binary equivalent of 65. One’s complement of 65 therefore would be, 1111 1111 1011 1110. One’s complement operator is represented by the symbol ~. Following program shows one’s complement operator in action.

main( )
{
int j, k ;
for ( j = 0 ; j <= 3 ; j++ )
{
printf ( "\nDecimal %d is same as binary ", j ) ;
showbits ( j ) ;
k = ~j ;
printf ( "\nOne’s complement of %d is ", j ) ;
showbits ( k ) ;
}
}

And here is the output of the above program...
Decimal 0 is same as binary 0000000000000000
One’s complement of 0 is 1111111111111111
Decimal 1 is same as binary 0000000000000001
One’s complement of 1 is 1111111111111110
Decimal 2 is same as binary 0000000000000010
One’s complement of 2 is 1111111111111101
Decimal 3 is same as binary 0000000000000011
One’s complement of 3 is 1111111111111100

In real-world situations where could the one’s complement operator be useful? Since it changes the original number beyond recognition, one potential place where it can be effectively used is in development of a file encryption utility as shown below:

/* File encryption utility */
#include "stdio.h"
main( )
{
encrypt( ) ;
}
encrypt( )
{
FILE *fs, *ft ;
char ch ;
fs = fopen ( "SOURCE.C", "r" ) ; /* normal file */
ft = fopen ( "TARGET.C”, "w" ) ; /* encrypted file */
if ( fs == NULL || ft == NULL )
{
printf ( "\nFile opening error!" ) ;
exit ( 1 ) ;
}
while ( ( ch = getc ( fs ) ) != EOF )
putc ( ~ch, ft ) ;
fclose ( fs ) ;
fclose ( ft ) ;
}

How would you write the corresponding decrypt function? Would there be any problem in tackling the end of file marker? It may be recalled here that the end of file in text files is indicated by a character whose ASCII value is 26.

No comments:

Post a Comment