我一直在尝试读取一个小端二进制文件。我希望首先找到文件中字符串的索引,从那里我可以开始读取数据。一旦获得索引,我将寻求提取学生信息。我成功地读取了字符串(名字和姓氏)。但是,我无法提取整数(年龄)。我感谢你的帮助:)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class BinaryData
{
private:
int age;
string firstName;
string lastName;
public:
BinaryData(){}
~BinaryData(){}
void readStudentData(string fileName)
{
//open the file and get its size
ifstream in(fileName.c_str(), ios::in | ios::binary);
in.seekg(0, ios::end);
int fileSize = in.tellg();
in.seekg(0, ios::beg);
//read the entire file into a buffer
string studentBuffer;
studentBuffer.resize(fileSize);
in.read(&studentBuffer[0], studentBuffer.size());
//move to the position where to start reading student info
int index = studentBuffer.find("StudentInfo");
if(index != 0 && index != std::string::npos)
{
//read the student info if the header is found
age = studentBuffer.substr(index, 3); //assume we are dedicating 3 characters for age
index += 3;
firstName = studentBuffer.substr(index, 10); //assume we are dedicating 10 characters for first name
index += 10;
lastName = studentBuffer.substr(index, 10); //assume we are dedicating 10 characters for first name
std::cout<< "The student name is: " << firstName << " " << lastName << ", they are " << age << " years old" << std::endl;
}
in.close();
}
}
我的代码的输出是:
The student name is: John Doe, they are **(some character)** years old
年龄数据看起来像:二进制文件中的 13 00 00 00 应该转换为 19,因为这是小尾数。
如有任何帮助,我们将不胜感激。谢谢!
以下是与系统无关的转换整数的代码:
#include <iostream>
#include <string>
#include <cstdint>
#include <stdexcept>
/**
* Converts a string containing binary data into a 64-bit unsigned integer.
* The string is interpreted in little endian format.
* If the string contains fewer than 1 byte or more than 8 bytes, an exception is thrown.
*
* @param binary_data The string containing the binary data.
* @return The 64-bit unsigned integer representation of the binary data.
*/
uint64_t convertToUInt64(const std::string& binary_data) {
if (binary_data.empty()) {
throw std::invalid_argument("Input string must contain at least 1 byte.");
}
if (binary_data.size() > sizeof(uint64_t)) {
throw std::length_error("Input string must contain no more than 8 bytes.");
}
uint64_t value = 0;
// Iterate over the string to construct the integer
for (size_t i = 0; i < binary_data.size(); ++i) {
// Cast each character to an unsigned byte and then shift it to the correct position
value |= static_cast<uint64_t>(static_cast<uint8_t>(binary_data[i])) << (i * 8);
}
return value;
}
您可以使用
string
中的示例二进制数据来调用它:
int main() {
// Binary data in a string, representing the value 19 in 3 bytes (little endian)
std::string binary_data = "\x13\x00\x00";
// Convert the binary data to a 64-bit unsigned integer
uint64_t value = convertToUInt64(binary_data);
// Output the integer value
std::cout << "The 64-bit unsigned integer value is: " << value << std::endl;
return 0;
}
我展示了一个通用函数,而不是仅接受 3 个字节的函数,以防还使用其他大小的字符串。如果你想要一个更小的整数,你可以检查该整数是否低于某个特定大小,然后分配。