You are to write two C methods to extract and insert bytes into an int. The firs
ID: 3542988 • Letter: Y
Question
You are to write two C methods to extract and insert bytes into an int.
The first is called GetNthByte that will take two arguments Value and ByteNdx, where ByteNdx is 0,1,2, or 3.
The prototype for GetNthByte is
unsigned char GetNthByte (int Value, int ByteNdx);
GetNthByte will return the byte specified by ByteNdx as we count the bytes from low to high 0 , 1, 2, 3.
Thus
GetNthByte(0xFACECAFE, 2) will return 0XCE, and NthByte(0xFACECAFE, 1) will return 0XCA.
PutNthByte will return a newly created value created by putting a new byte into the byte specified by ByteNdx, again as we count the bytes from low to high 0 , 1, 2, 3.
The prototype for PutNthByte is
unsigned int PutNthByte (int Value, int ByteNdx, unsigned char NewByte);
Use the %x format descriptor for output.
Some interesting possible cases to try for GetNth and PutNth
Value ByteNdx NewByte
-1 2 0xA
0xDEADBEEF 3 'A'
2^32 - 1 2 0
127 3 0xF
Explanation / Answer
Here is the code I have written for you. Just input any number and it will give you all its bytes.
#include <stdio.h>
int main()
{
int x;
scanf("%d",&x);
int i;
for (i = 0; i < sizeof(x); ++i) {
unsigned char byte = *((unsigned char *)&x + i);
printf("Byte %d = %u ", i, (unsigned)byte);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.