【问题标题】:How to set a value in a specific byte?如何在特定字节中设置值?
【发布时间】:2013-11-28 00:14:06
【问题描述】:

我正在使用 MapViewOfFile() 和 SharedMemory。我能够逐字节读取内存内容!现在我想知道,如何将新的十六进制值设置为特定字节?由于我的代码,我希望在我的第二个 console.log 中,十六进制值 0xffc8 在单元格 83 中。不幸的是,情况并非如此。

// main method 
FILE * pBuf = (FILE*) MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
...
int d;
BYTE dbgByte;
for(d = 0; d < 86; d++){ 
    dbgByte = *((PBYTE) pBuf + (d));
    printf("DEBUG byte %i hexvalue %hhx \n", d, (char) dbgByte); 
    printf("DEBUG byte %i int %i \n", d, (int) dbgByte); 
}
// DEBUG - END
for(d = 0; d < 86; d++){ 
    if (d == 83){ // 0xffc8 = 200
    BYTE writeByte1;
    writeByte1 = *((PBYTE) pBuf + (d));
    writeByte1 = 0xffc8;
    }
}
// DEBUG 2 - START
for(d = 0; d < 86; d++){ 
    dbgByte = *((PBYTE) pBuf + (d));
    printf("DEBUG byte %i hexvalue %hhx \n", d, (char) dbgByte); 
    printf("DEBUG byte %i int %i \n", d, (int) dbgByte); 
}
// DEBUG - END
...

更新:尝试了比尔的建议 - 不幸的是,这也不起作用:

if (d == 84){ // 0x42 = 66
    *((PBYTE) pBuf + (d)) = 0x42;
}

UPDATE-2:尝试了 Oblivious 船长的建议 - 不幸的是,写作程序不起作用。我在 debug-3 日志记录语句中看不到十六进制值 42。

for(d = 0; d < 86; d++){ 
    byte = pBuf[d];
    printf("DEBUG-1 ");
    printf("hex:  %hhx; ", byte);
    printf("char:  %c; ", (char) byte);
    printf("dec: %i; ", (int) byte);
    printf(" byte %i; ", d);
    printf("\n");
    if (d == 84){ // 0x42 = 66
        pBuf[d] = 0x42;
        printf("DEBUG-3 ");
        printf("hex:  %hhx; ", byte);
        printf("char:  %c; ", (char) byte);
        printf("dec: %i; ", (int) byte);
        printf(" byte %i; ", d);
        printf("\n");
    }
}

【问题讨论】:

  • 你打算如何将0xffc8 放在一个字节中?

标签: c++ c shared-memory


【解决方案1】:

您可以通过将pBuf 声明为std::uint8_t*unsigned char*BYTE* 而不是FILE* 来大大简化读写。

std::uint8_t* pBuf = static_cast<std::uint8_t*>(
    MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE));

这将允许您将数据作为数组进行操作。然后,您可以更改从以下读取字节的方式

var = *((PBYTE) pBuf + (d));

var = pBuf[d];

这也使得更改值变得同样容易。

pBuf[d] = var;

【讨论】:

  • 感谢您的建议队长 - 无论如何,我还无法设置新值。
  • 谢谢队长,现在可以了。我看错了变量:-)
【解决方案2】:

这段代码:

writeByte1 = *((PBYTE) pBuf + (d));
writeByte1 = 0xffc8;

pBuf中的值复制到局部变量writeByte1,然后将局部变量更改为其他变量。

尝试写入缓冲区:

*((PBYTE) pBuf + (d)) = 0xff;
*((PBYTE) pBuf + (d+1)) = 0xc8;

编辑回复:

修改内存的代码有效,你可以在这里看到:https://ideone.com/EKsvmU 问题可能在于您使用MapViewOfFile 的方式。例如,MapViewOfFile() 不会返回 FILE*

【讨论】:

  • 谢谢比尔 - 我试过你的例子(见我编辑过的帖子) - 不幸的是没有成功!
  • 所以你可以提出更好的问题,你应该知道说“没有成功”是没有帮助的。说出你看到的,以及你期望看到的。
  • 啊,好吧,我希望看到我的新设置值('42(十六进制)'),但我看到了旧值,'00'。
  • @Jochen:那么您可能正在错误地处理 MapViewOfFile。它不会返回 FILE*
  • 另外,“volatile”关键字的存在是有原因的.. ;-)
猜你喜欢
  • 2020-10-27
  • 2016-07-22
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
相关资源
最近更新 更多