Need some help finishing these functions: /* We do support the IEC 559 math func
ID: 3806014 • Letter: N
Question
Need some help finishing these functions:
/* We do support the IEC 559 math functionality, real and complex. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
// selected puzzles for Spring 2017
/*
* evenBits - return word with all even-numbered bits set to 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 1
*/
int evenBits(void) {
return 2;
}
/*
* copyLSB - set all bits of result to least significant bit of x
* Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int copyLSB(int x) {
return 2;
}
/*
* reverseBytes - reverse the bytes of x
* Example: reverseBytes(0x01020304) = 0x04030201
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 25
* Rating: 3
*/
int reverseBytes(int x) {
return 2;
}
/*
* isPositive - return 1 if x > 0, return 0 otherwise
* Example: isPositive(-1) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 3
*/
int isPositive(int x) {
return 2;
}
/*
* isLessOrEqual - if x <= y then return 1, else return 0
* Example: isLessOrEqual(4,5) = 1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
* Rating: 3
*/
int isLessOrEqual(int x, int y) {
return 2;
}
Explanation / Answer
/* We know 0x55 = 10101010, To create a number with all even bits we will shift 101010 to the left 8, 16, and 24 bits to fill the remainder of a 32 bit int without using 0x55555555. */
int evenBits(void) {
int x;
int num;
x = 0x55;
num = (x + (x<<8) + (x<<16) + (x<<24));
return num;
};
int copyLSB(int x)
{
//isolates the last bit
x = x&0x1;
//shifts the last bit to the most significan bit
x = x<<31;
//copies the sign bit to all the bits
x = x>>31;
return x;
}
int reverseBytes(int x)
{
int newbyte_0 = (x >> 24) & 0xff;
int newbyte_1 = (x >> 8) & 0xff00;
int newbyte_2 = (x << 8) & 0xff0000;
int newbyte_3 = x << 24;
return newbyte_0 | newbyte_1 | newbyte_2 | newbyte_3;
}
/*A number is positive if it is not negative and non zero.Hence shift the most significant bit and then do logical not to see if it is less than 0.Then & that with whether x is zero or not.*/
int isPositive(int x)
{
x = (!(x>>31))&!!x;
return x;
}
int isLessOrEqual(int x, int y) {
int y_sign = (y >> 31) & 1; //copies significant bit of y to all places and returns 1 if negative, 0 if positive
int x_sign = (x >> 31) & 1;
int z = (!(y_sign^x_sign)) & (((x+~y)>>31) & 1); //checks whether x and y are the same, one is negative or not, and then checks if x is less than y
return z|((!y_sign) & x_sign); //if x is less than y and the signs are the same or one variable is negative
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.