【发布时间】:2017-09-07 20:54:57
【问题描述】:
我正在尝试编写一个函数来访问一个字节并将其更改为另一个。我在管理指针时遇到了麻烦。
有人可以帮我修复这段代码,让 px 指向地址,然后我可以增加 pc (这与 px 相同,但就像 char 以避免增加太多字节),然后替换 mem 中的内容用其他东西定位电脑?
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;
}
我得到这样的返回值: 305419947 305441656 313218680 2872333944
当我想得到这样的值时:
replace_byte(0x12345678, 0xAB, 2) --> 0x12AB5678 replace_byte(0x12345678, 0xab, 0) --> 0x123456AB
【问题讨论】:
-
究竟是什么不工作(除了你应该写
return x而不是return printf...)? -
尊重我们的时间正确编写代码这是什么鬼:
return printf("%s\n", );); -
根据您完全有意义的编辑,整数以 4 个字节存储,每个位重 1,2,4,8,16,...... 替换一个字节将彻底改变数字。如果您希望输出看起来像 replace_byte(0x12345678, 0xAB, 2) --> 0x12AB5678,那么您需要分别写入每个字节。
-
@Jas 那么如果我获取地址然后递增,我可以分别访问每个字节并在其内存位置编辑值?对?这就是我想要做的,但显然我做错了什么......
-
@Ozzoned 当然,您可以单独访问每个字节并根据需要对其进行编辑,并且您的操作方式确实是正确的。字节正在被修改。问题是您的输出不是您期望的正确?这是因为计算机不会将整数解释为 4 个 单独 字节,而是将它们解释为 单个 大数。在某处阅读更多信息,您的疯狂数字是正确的。整数的第一个字节从 0 到 255,下一个更重,从 255 到 32,767。因此,如果您将第二个字节增加 ONE,则更改将是巨大的。