You are to write two C methods to extract and insert bytes into an int. The firs
ID: 3542987 • 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
For the (n+1) byte:
int x = ((unsigned char *)(&number))[n];
For the (n+1)th byte from least to most significant on big-endian machines:
int x = ((unsigned char *)(&number))[sizeof(int) - 1 - n];
For the (n+1)th byte from least to most significant (any endian):
int x = ((unsigned int)number >> (n << 3)) & 0xff;
Of course, these all assume that n < sizeof(int), and that number is an int
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.