Frelonics
HomeServicesScrumAbout UsSample: MATLABSample: C++

#include <iostream.h>
#include <stdio.h>
#include <string.h>


​////////////////////////////////////////
// short program to demonstrate bitwise oporators


////////////////////////////////////////
// fn_minmax -- constrain an input value to range of a byte
// unsigned char makes it come back as a byte instead of a one char 'string'
// this will most likely vary by compiler
unsigned char fn_minmax( int A ) {
  if ( A < 0 )
    A = 0;
  else if ( A > 255 )
    A = 255;

  return A;
} // fn_minmax


////////////////////////////////////////
void Display( int A, int B ) {
  cout << " " << A << " ^ " << B << " = " << (A ^ B) << endl;
} // Display

////////////////////////////////////////
void fn_xor( unsigned int A, unsigned int B ) {
  charlstr[255];

  A = fn_minmax(A);
  B = fn_minmax(B);

  strcpy( lstr, "" );
  sprintf( lstr, "%02X ^ %02X -> %02X", A, B, (A^B) );


  cout << lstr << endl;
} // fn_xor

////////////////////////////////////////
void fn_and( unsigned int A, unsigned int B ) {
  charlstr[255];

  A = fn_minmax(A);
  B = fn_minmax(B);

  strcpy( lstr, "" );
  sprintf( lstr, "%02X & %02X -> %02X", A, B, (A&B) );

  cout << lstr << endl;
} // fn_and


////////////////////////////////////////
// demonstrate bitwise logic operations 
int main(int argc, char *argv[])
{
  cout << "Display XOR results\n" << endl << endl;


  Display( 1, 5);
  fn_xor( 1, 5 );
  fn_and( 1, 5 );
  cout << endl;

  Display( 1, 15);
  fn_xor( 1, 15 );
  fn_and( 1, 15 );
  cout << endl;

  Display( 15, 255);
  fn_xor( 15, 255 );
  fn_and( 15, 255 );
  cout << endl;

  cout << "\nDone." << endl;
  return 0;
}

Simple Demonstration of Bitwise AND and XOR