Explanation of Solution
Function definition for “replace_byte()” function:
The implementation for “replace_byte()” function is given below:
//Header file
#include <stdio.h>
#include <assert.h>
//Function definition for replace byte function
unsigned replace_byte(unsigned x, int i, unsigned char b)
{
//Check if value of "i" is less than "0", then
if (i < 0)
{
//Display error message
printf("error: value of i is negetive\n");
return x;
}
/* Check if value of "i" is greater than "sizeof(unsigned)-1", then */
if (i > sizeof(unsigned)-1)
{
//Display error message
printf("error: value of i is too high");
return x;
}
/* Assign the value of mask that is for byte
in general, 1 bye = 8 bits and then << implies *8 */
unsigned m = ((unsigned) 0xFF) << (i << 3);
//Defines the byte position
unsigned bytePosition = ((unsigned) b) << (i << 3);
//Return given value
return (x & ~m) | bytePosition;
}
//Main function
int main(int argc, char *argv[])
{
/* Call replace_byte function for replace byte 2 in given "x" by byte "0xAB" */
unsigned replaceByte2 = replace_byte(0x12345678, 2, 0xAB);
/* Call replace_byte function for replace byte 0 in given "x" by byte "0xAB" */
unsigned replaceByte0 = replace_byte(0x12345678, 0, 0xAB);
/* Check if the replaced byte equals to given value using "assert" function */
assert(replaceByte2 == 0x12AB5678);
assert(replaceByte0 == 0x123456AB);
return 0;
}
The given code is used to return an unsigned value in which byte “i” of argument “x” has been replaced by “b”...
Want to see the full answer?
Check out a sample textbook solutionChapter 2 Solutions
EBK COMPUTER SYSTEMS
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY