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

Required Task 1A: Read the reference [1] on bitwise operations. Write the functi

ID: 3793628 • Letter: R

Question

Required Task 1A: Read the reference [1] on bitwise operations. Write the function which returns the middle 16 bits (bit 8 - bit 23) as 16 bits return value (e.g. unsigned short). In main routine, test and verify the function of middle () by assigning 0 times 12345678. Capture the console output and attach it to your report. The output should be 0 times 3456. Write middle function: unsigned short middle (unsigned int a) {} Declare A in your main() function and call middle() to see if it returns 0 times 3456: unsigned int A = 0 times 12345678; Print out the return value of middle();

Explanation / Answer

This can be solved easily using the right-shift binary operator >>.

First, let me write the code. Then I will explain.

Source-Code:

#include<stdio.h>

unsigned short middle(unsigned int a)
{
unsigned short s = a >> 8;
return s;
}

void main()
{
unsigned int a = 0x12345678;

unsigned short answer = middle(a);

printf("%#x", answer);
}

This code is displaying 0x3456 in my output window.

Explanation:

See, here, int is of 4-bytes and short is of 2-bytes. So, when we assign the int value to the short variable, only the lower 16-bits are copied in a short type variable. This is applicable in C. However, the other bits are lost but we can get lower half-portion of the data by assigning an int value to a short variable.

You need to show bits 8-23. Here, the bits are calculated from right to left. So, the rightmost bit is considered 0. And then we go to the left side till MSB 31 which is at leftmost position.

Now, if we directly assign our int to short, it will assign 0-15 i.e. first 15 bits to short. But we want 8-23 bits. That means, from the right side, if we remove the 8 bits (0 to 7), we get our desired bits in the lower half portion. So, for this purpose, bit-wise shift right operator should be used.

How many bits we want to move to right? 8. So, >> 8 is applied and the value is stored in a short variable which is returned from the middle() function.

Now, to display that result, I stored it in answer variable and to display it in the same format 0x... %#x is used. # is used here to print 0x and %x is used for hexadecimal value which is 3456 in this case.

Do comment if there is any query. Thank you. :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote