I'm trying to write a function that will access a byte and change it for another. I'm having trouble managing the pointers.
Can someone help me fix this code so that px points to the address, and i can then increment pc (which is the same as px but just as char to avoid incrementing by too many bytes) and then replace what is at mem location pc with something else?
unsigned replace_byte(unsigned x, int i, unsigned char b){
unsigned int* px = &x; //Takes initial address of first byte.
unsigned char* pc= (unsigned char*)px; //Recast it too char
//pointer to avoid incrementing by too many bytes
if (i==0) {
*pc= b; //if i is 0 then replace the byte at mem location pc
//with b
}
if (i==1) { //if i is 1 or more then inc by that much and replace
pc = pc+1;
*pc= b;
}
if (i==2) {
pc=pc+2;
*pc= b;
}
if (i==3) {
pc=pc+3;
*pc= b;
}
return x;
}
I'm getting return values like this: 305419947 305441656 313218680 2872333944
When i would want to get values like this:
replace_byte(0x12345678, 0xAB, 2) --> 0x12AB5678 replace_byte(0x12345678, 0xab, 0) --> 0x123456AB