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

I do not understand this requirement in this lab. Extract byte n from word x? Fo

ID: 3750712 • Letter: I

Question

I do not understand this requirement in this lab. Extract byte n from word x?

For this example: getByte(0x12345678,1) = 0x56

I changed 0x12345678 into binary, we can get 0000 0000 0001 0010 0011 0100 0101 0110 0111 1000

and change 0x56 into binary. 0000 0000 0101 0110

If I Extract byte 1 from word 0x12345678, we can get the answer by from right to left: 0.

If I Extract byte 4 from word 0x12345678, we can get the answer by from right to left: 1000

If I Extract byte 8 from word 0x12345678, we can get the answer by from right to left: 0111 1000

Why this answer is 0x56, for binary is  0000 0000 0101 0110 for n =1?

/*
* getByte - Extract byte n from word x
* Bytes numbered from 0 (LSB) to 3 (MSB)
* Examples: getByte(0x12345678,1) = 0x56
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 2
*/
int getByte(int x, int n) {
// 0<<3 = 0, 1<<3 = 8, 2<<3 = 16, 3<<3 = 24
// each byte starts from (n<<3)th bit.
int t = x >> (n << 3);
// get 8 bits = 1 byte
int r = t & 255;
return r;
}

Explanation / Answer

Given-

(0000 0000) [ BYTE 04] (0001 0010) [ BYTE 3] (0011 0100) [ BYTE 2] (0101 0110) [ BYTE 1] (0111 1000) [ BYTE 0]

8 bits= 1 byte

So if someone asks me to return byte 1, for 0x12345678 we return bits from 9 to 16, ie (0101 0110) in given example.

From given code-

int getByte(int x, int n) {
int t = x >> (n << 3); //will move byte to Lower index, say if n=1, n<<1 will give 8 and bits from 9 to 16 will move to Lower indexes

int r = t & 255; //then we AND with 1111 1111 to get 1 BYTE
return r;
}

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