我想从二进制(.bin)文件中读取一组256个字节并将其存储到缓冲区中。然后我想将每个字节移动到char向量的向量中。此外,我想读取向量中的char值并获取该字节的二进制值的相应整数值。这就是我接触它的方式:
typedef unsigned char BYTE;
vector< vector<BYTE> > pMem (256, vector<BYTE> (256, '0'));
ifstream binStream;
binStream.open("BACKING_STORE.bin", ios::binary | ios::in );
// allocate memory:
char * buffer = new char [256];
binStream.seekg(0, binStream.beg);
binStream.read(buffer, 256);
for( i = 0; i < 256; i++ )
pMem[0][i] = buffer[i];
for( i = 0; i < 256; i++ )
{
cout << "Physical memory char contents at 0[" << i << "]: " << pMem[0][i] << endl;
int x = pMem[0][i];
cout << "Physical memory integer contents at 0[" << i << "]: " << x << endl;
}
但是当我打印出值时,我会得到如下结果:
Physical memory char contents at 0[237]:
Physical memory integer contents at 0[237]: 0
Physical memory char contents at 0[238]:
Physical memory integer contents at 0[238]: 0
Physical memory char contents at 0[239]: ;
Physical memory integer contents at 0[239]: 59
Physical memory char contents at 0[240]:
Physical memory integer contents at 0[240]: 0
Physical memory char contents at 0[241]:
Physical memory integer contents at 0[241]: 0
Physical memory char contents at 0[242]:
Physical memory integer contents at 0[242]: 0
Physical memory char contents at 0[243]: <
Physical memory integer contents at 0[243]: 60
Physical memory char contents at 0[244]:
Physical memory integer contents at 0[244]: 0
Physical memory char contents at 0[245]:
Physical memory integer contents at 0[245]: 0
Physical memory char contents at 0[246]:
Physical memory integer contents at 0[246]: 0
Physical memory char contents at 0[247]: =
Physical memory integer contents at 0[247]: 61
Physical memory char contents at 0[248]:
Physical memory integer contents at 0[248]: 0
Physical memory char contents at 0[249]:
Physical memory integer contents at 0[249]: 0
Physical memory char contents at 0[250]:
Physical memory integer contents at 0[250]: 0
Physical memory char contents at 0[251]: >
Physical memory integer contents at 0[251]: 62
Physical memory char contents at 0[252]:
Physical memory integer contents at 0[252]: 0
Physical memory char contents at 0[253]:
Physical memory integer contents at 0[253]: 0
Physical memory char contents at 0[254]:
Physical memory integer contents at 0[254]: 0
Physical memory char contents at 0[255]: ?
Physical memory integer contents at 0[255]: 63
这显然是错误的输出。有人可以解释一下我做错了什么以及如何做到这一点?
答案 0 :(得分:1)
当你有:
char c = 'a';
std::cout << c << std::endl;
输出将是
a
当c
的值对应于非打印字符之一时,输出因系统而异。在你的情况下,你得到空白输出。
如果要打印'a'
的整数表示,则必须进行转换。
std::cout << (int)c << std::endl;
或
int x = c;
std::cout << x << std::endl;
我希望你能得到所有解释。