Week 4 Exercise: Bits And XOR Encryption

Chris Tralie

You can obtain the code for today's exercise here:

git clone https://github.com/ursinus-cs174-s2022/Week4_Bits.git

Exercise 1: Printing numbers in binary

I've provided a file num2binary.cpp which takes in an int as a command line argument and prints out a corresponding 32-bit unsigned binary string using the "textbook algorithm" for doing this. For example,

will print out 01110111001101011001010000000000

Your job will be to fill out a file mynum2binary.cpp that accomplishes the same thing, but only using bitwise operators:

  • Allowed: Binary AND (&), Binary OR (|), Binary XOR (^), Left Binary Shift (< <), and Unsigned Right Binary Shift (> > >)
  • NOT Allowed: +, -, /, *, %

Exercise 2: Converting a binary string to a number

I've provided a file binary2num.cpp which takes a binary string as a command line argument and which prints out the number corresponding to it. For example

will print out 27

Your job will be to fill out a file mybinary2num.cpp that accomplishes the same thing, but only using bitwise operators

Exercise 3: XOR Encryption

Fill in the file encrypt.cpp to implement XOR encryption/decryption. The command line arguments refer to three files:

  1. The first file is thought of either as the "plain text" (original message) or the "cipher text" (encrypted message)
  2. The second file is the "cipher," or what we use to encrypt information
  3. The third file is the output file which stores the cipher text or the decrypted text

For example, if you run

It will decrypt the bytes in hidden by XORing with the bytes in password.txt and save the result to decrypted.txt. If this works, you should be able to read the text in decrypted.txt

The steps to accomplish this are as follows:

  1. Load in file1
  2. Load file2
  3. Loop through and replace each byte in file1 with the XOR of the corresponding byte in file2. If file2 reaches the end, loop back to the beginning
  4. Write out the resulting XORED file