如何在特定字节中设置值?

时间:2013-11-28 00:14:06

标签: c++ c shared-memory

我正在使用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:尝试了Captain Oblivious建议 - 遗憾的是写作程序没有用。我在debug-3 logging语句中看不到十六进制值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");
    }
}

2 个答案:

答案 0 :(得分: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*

答案 1 :(得分:2)

通过将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;