【发布时间】:2013-09-07 00:35:02
【问题描述】:
我正在尝试打开一个 wav 文件,读取它,将缓冲区转换为整数数组,然后将其转换回来并写入。
int main(){
ifstream file ("C:\\Documents\\ParadigmE3-shortened.wav",std::ios_base::out | std::ios_base::binary);
char * header = new char[50000044];
file.read(header, 50000044);
cout << header[0] << endl;
unsigned int * header_int = new unsigned int[50000044];
for(unsigned int i = 0; i < sizeof(header); i++){
header_int[i] = header[i];
}
char * writefile = new char[50000044];
for(unsigned int i = 0; i < sizeof(header); i++){
itoa(header_int[i], &writefile[i], 10);
}
cout << writefile[0] << endl;
ofstream newfile ("C:\\Documents\\ParadigmE3-modified.wav", std::ios_base::out | std::ios_base::binary);
newfile.write(writefile, 50000044);
}
目前,这打印:
R
8
表示它在转换过程中改变了数据。我怎样才能让它正常工作?
经过一些建议,学习我可以对char变量进行计算,我重新编写了代码,现在是:
int main(){
// Create file variable with file
ifstream file ("C:\\Documents\\ParadigmE3-shortened.wav",std::ios_base::out | std::ios_base::binary);
// Read the first 15040512 bytes to char array pointer, called header
char * header = new char[15040512];
file.read(header, 15040512);
// Copy contents of header to writefile, after the 44'th byte, multiply the value by 2
char * writefile = new char[15040512];
for(int i = 0; i < sizeof(header); i++){
if(i<44) writefile[i] = header[i];
if(i>=44) writefile[i] = 2 * header[i];
}
// Copy the contents of writefile, but at the 44th byte, divide it by 2, returning it to its original value
for(int i = 0; i < sizeof(header); i++){
if(i<44) writefile[i] = writefile[i];
if(i>=44) writefile[i] = .5 * writefile[i];
}
// Create file to write to
ofstream newfile ("C:\\Documents\\ParadigmE3-modified.wav", std::ios_base::out | std::ios_base::binary);
// Write writefile to file
newfile.write(writefile, 15040512);
}
但是,在播放时(在 Windows Media Player 中),它没有播放,所以它显然不是我想要的原始文件。
【问题讨论】:
-
这有很多问题,我什至不知道从哪里开始。你到底想达到什么目的?
-
50000044不能被分成8的块而没有余数。 -
不,它读取
char数组缓冲区。而且您不必将其转换为int数组来对其执行计算,您可以很好地对char值进行数值运算。在某种程度上,char只是一个小的int。 -
是的。就像我说的,
char只是一个小的int。 (您确实需要注意char可能是“有符号”或“无符号”这一事实 - 即,它可能表示值 -128 到 127,或者它可能表示 0 到 255,具体取决于您使用的特定编译器使用。) -
(对于某些操作,您需要将数字结果“转换”为
char以将其分配回char:char result = (char) some + mathematical * expression;。这是因为char是“加宽的” " 到int以执行大多数数学运算。)