In C language Write code for a function called problem2 whic

In C language.

Write code for a function called problem2 which takes an unsigned long int x, and returns 1 if any even-numbered bit is set to 1. Follow the assumptions below. Assumptions Integers are 64-bits long and represented in twos-complement form. Right shifts of signed data are performed arithmetically. Bits are numbered right to left from 0 to 63 Forbidden Casting, either explicit or implicit. Relative comparison operators(, =) Division, modulus, and multiplication. Conditionals(if or?:), loops, switch statements, function calls, and macro invocations. Casting, either explicit or implicit. Legal operations ! - & - 1 + Even with these rules, you should try to make your code readable by choosing descriptive variable names and using comments to describe the logic behind your solutions. as an example, the following code extracts the most sign cant byte from integer argument x:/* get most significant byte from x */int get_msb(int x){/* shift buy w-8 */int shift_val = (sizeof(int)-1) shift_val;/* zero all but LSB */return xright & oxFF;} write code for the function with the following prototype:/* problem2 return 1 if any even-numbered bit in x is set to 1 * examples problem2(5) = 1, problem2(10) = 0, problem2(6) = 1 */int problem2(unsingned long int x)

Solution

a// According to problem, solution involves the identification of any even bit set

// This can be done in two steps:
// 1. First of all, we need to mask all the odd bits as they aren\'t even required, i.e. turn all the odd bits 0.
// It can be done by ANDing it with 0x5555555555555555 (as unsigned long int is of 64 bits size i.e. 16 nibbles, therefore 16 5s)
//
// 2. After masking in above step, if the result has any even bit set, then ORing it recursively with it\'s half and removing the half ORed by right shifting, will return 1 left at least significant bit at last.
//
// 3, Final step is to return the result after ANDing with 0xFF to convert it to int

int problem2(unsigned long int x)

{
       // Turn off all the odd bits by anding with a number with all the even bits set,i.e., Typical turning off mask.
unsigned long int no_odd_bits_set = x & 0x5555555555555555;

// Recursively ORing and right shifting to identify whether any bit set.
unsigned long int result = no_odd_bits_set;
result = result | result>>32;
result = result | result>>16;
result = result | result>>8;
result = result | result>>4;
result = result | result>>2;
  
// Return the result in integer
return 0xFF & result;
}

In C language. Write code for a function called problem2 which takes an unsigned long int x, and returns 1 if any even-numbered bit is set to 1. Follow the assu

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site