文本文件的二进制输入
Binary input of text file
Programming Principles and Practice 在第 11 章中说:
“在内存中,我们可以将数字 123 表示为整数值(每个 int 占 4 个字节)或字符串值(每个字符占 1 个字节)”。
我在读取二进制文本文件时试图了解内存中存储的内容。
所以我在写vector v.
的内容
如果输入文件包含此文本:“测试这些词”
输出文件显示这些数字:1953719668 1701344288 1998611827 1935962735 168626701 168626701 168626701 168626701 168626701 168626701
我尝试将“test”的每个字符都转换为二进制
我有 01110100 01100101 01100101 01110100
如果我将其视为 4 字节的整数并将其转换为十进制,我将得到 1952802164,这与输出仍然不同。
这是如何正确完成的,所以我可以理解发生了什么?谢谢!
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<sstream>
#include <fstream>
#include <iomanip>
using namespace std;
template <class T>
char *as_bytes(T &i) // treat a T as a sequence of bytes
{
void *addr = &i; // get the address of the first byte of memory used to store the object
return static_cast<char *>(addr); // treat that memory as bytes
}
int main()
{
string iname{"11.9_in.txt"};
ifstream ifs {iname,ios_base::binary}; // note: stream mode
string oname{"11.9_out.txt"};
ofstream ofs {oname,ios_base::binary}; // note: stream mode
vector<int> v;
// read from binary file:
for(int x; ifs.read(as_bytes(x),sizeof(int)); ) // note: reading bytes
v.push_back(x);
for(int x : v)
ofs << x << ' ';
}
假设您使用的是 little-endian 机器(例如 x86)和 ASCII-compatible 字符代码(例如 Shift_JIS 和 UTF-8)。
test
表示为74 65 73 74
二进制数据。
使用little-endian,muitl-byte整数的高字节被放置到高地址。
因此,将thes作为4字节整数读取,将被解释为0x74736574
,十进制为1953719668
。
Programming Principles and Practice 在第 11 章中说: “在内存中,我们可以将数字 123 表示为整数值(每个 int 占 4 个字节)或字符串值(每个字符占 1 个字节)”。
我在读取二进制文本文件时试图了解内存中存储的内容。 所以我在写vector v.
的内容如果输入文件包含此文本:“测试这些词”
输出文件显示这些数字:1953719668 1701344288 1998611827 1935962735 168626701 168626701 168626701 168626701 168626701 168626701
我尝试将“test”的每个字符都转换为二进制 我有 01110100 01100101 01100101 01110100 如果我将其视为 4 字节的整数并将其转换为十进制,我将得到 1952802164,这与输出仍然不同。
这是如何正确完成的,所以我可以理解发生了什么?谢谢!
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<sstream>
#include <fstream>
#include <iomanip>
using namespace std;
template <class T>
char *as_bytes(T &i) // treat a T as a sequence of bytes
{
void *addr = &i; // get the address of the first byte of memory used to store the object
return static_cast<char *>(addr); // treat that memory as bytes
}
int main()
{
string iname{"11.9_in.txt"};
ifstream ifs {iname,ios_base::binary}; // note: stream mode
string oname{"11.9_out.txt"};
ofstream ofs {oname,ios_base::binary}; // note: stream mode
vector<int> v;
// read from binary file:
for(int x; ifs.read(as_bytes(x),sizeof(int)); ) // note: reading bytes
v.push_back(x);
for(int x : v)
ofs << x << ' ';
}
假设您使用的是 little-endian 机器(例如 x86)和 ASCII-compatible 字符代码(例如 Shift_JIS 和 UTF-8)。
test
表示为74 65 73 74
二进制数据。
使用little-endian,muitl-byte整数的高字节被放置到高地址。
因此,将thes作为4字节整数读取,将被解释为0x74736574
,十进制为1953719668
。