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

You just started working for a company that is implementing a set of procedures

ID: 3561173 • Letter: Y

Question

You just started working for a company that is implementing a set of procedures to operate on a data structure where 4 signed bytes are packed into a 32-bit unsigned. Bytes within the word are numbered from 0 (least significant) to 3 (most significant). You have been assigned the task of implementing a function for a machine using two's-complement arithmetic and arithmetic right shifts with the following prototype:

/*Declaration of data type where 4 bytes are packed into an unsigned*/

typedef unsigned packed_t;

/*Extract byte from word. Return as signed integer*/

int xbyte(packed_t word, int bytenum);

That is, the fuction will extract the designated byte and sign extend it to be a 32-bit int.

Your predecessor (who was fired for incompetence) wrote the following code:

/*Failed attempt at xbyte*/

int xbyte(packed_t word, int bytenum) {

return (word >> ( bytenum << 3 ) ) & 0xFF ; }

A. What is wrong with this code?

B. Give a correct implementation of the function that uses only left and right shifts, along with one subtraction.

Explanation / Answer

A.

The code does not perform the sign extension. It will not work properly for negation numbers.

B.

The correct implementation of the function is as follows:

int xbyte(packed_t word, int bytenum)

{

int Lbyte = word << ((3 - bytenum) << 3);

return Lbyte >> 24;

}

The above code uses only left and right shifts along with one subtraction. First, perform the left shift after that the right shift. After performing the left shift, the most significant bit is at the position 31. The right shift by 24, moves the byte into the correct position and performs the sign extension.

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