You are expressly forbidden to: 1. Use any control constructs such as if, do, wh
ID: 3745880 • Letter: Y
Question
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 &&, 1,-, or ?: 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 <bitset>
using namespace std;
void printBinary(int a) {
std::bitset<32> y(a);
std::cout << y << endl;
}
int evenBits(void) {
// The below is a 32 bit representation of number where the even bits are set
// A means 1010 in binary, Because we are taking hexadecimal number
int x = 0x0000000A;
x = x | (x << 4); // x = 0x000000AA;
x = x | (x << 8); // x = 0x0000AAAA;
x = x | (x << 16); // x = 0x0000AAAA;
return x;
}
// 1 is represented as 0x00000001 in binary
// so 1's complement is 0xFFFFFFFE
// for finding 2' complement, we need to add 1
// so the result becomes 0xFFFFFFFF.. that is all
// bits set
int minusOne(void) {
int x = 1;
x = ~x;
return x+1;
}
int copyLSB(int x) {
x = x & 1; // leave only the last bit in x
// for x = 0, ~x is OxFFFFFFFF, on adding 1, it will become 0x00000000
// for x = 1, ~x is 0xFFFFFFFE, on adding 1, it becomes 0xFFFFFFFF.
x = ~x;
return x+1;
}
int main()
{
printBinary(evenBits());
printBinary(minusOne());
printBinary(copyLSB(5));
printBinary(copyLSB(6));
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.