Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Must be written in C++ using only bitwise operators, 4 different problems, an ex

ID: 3884718 • Letter: M

Question

Must be written in C++ using only bitwise operators, 4 different problems, an explanation of the code and how it works is necessary

You are expressly forbidden to: 1. Use any control constructs such as if, do, while, for, switch, etc. 2. Define or use any macros. 3. Define any additional functions in this file. 4. Call any functions. 5. Use any other operations, such as &&, II, -, or ?: 6. Use any form of casting. 7. Use any data type other than int. This implies that you cannot use arrays, structs, or unions. You may assume that your machine: 1. Uses 2s complement, 32-bit representations of integers. 2. Performs right shifts arithmetically. 3. Has unpredictable behavior when shifting an integer by more than the word size.

Explanation / Answer

#include <iostream>
#include <cmath>
using namespace std;

int anyOddBit(int x) {
   x ^= x >> 16;
   x ^= x >> 8;
   x ^= x >> 4;
   x &= 0xf;
   return (0x6996 >> x) & 1;
}

int isNegative(int x){
    if(x<0) return 1;
    else return 0;
}

int getByte(int x, int n)
{
    return (x >> (n << 3)) & 0xFF;
}

int divpwr2(int x,int n){
  
    return x/(pow(2,n));
}

int main ()
{
int z;

z=isNegative(-9);
cout << "The result is " << z<<endl;
   z=anyOddBit(5);
cout << "The result is " << z<<endl;

   z=anyOddBit(7);
cout << "The result is " << z<<endl;

   z=divpwr2(-33,4);
cout << "The result is " << z<<endl;

int x = 0xAABBCCDD;
    int n;

    for (n=0; n<=3; n++) {
        printf("byte %d of 0x%X is 0x%X ",n,x,getByte(x,n));
    }

}