📜  将Struct数据类型转换为十六进制字符串,反之亦然

📅  最后修改于: 2021-05-26 00:49:35             🧑  作者: Mango

系统中生成的大多数日志文件都是二进制(0,1)十六进制(0x)格式。有时您可能需要将此数据映射为可读格式。

将此十六进制信息转换为系统定义的数据类型(例如“ int / 字符串/ float”)相对容易。另一方面,当您有一些用户定义的数据类型(例如“ struct”)时,过程可能会很复杂。

遵循以下基本程序将有助于您进行上述操作。在现实世界中实现时,您需要更多的错误处理。

// C++ Program to convert a 'struct' in 'hex string'
// and vice versa
#include 
#include 
#include 
#include 
  
using namespace std;
  
struct Student_data
{
    int  student_id;
    char name[16];
};
  
void convert_to_hex_string(ostringstream &op,
                      const unsigned char* data, int size)
{
    // Format flags
    ostream::fmtflags old_flags = op.flags();
  
    // Fill characters
    char old_fill  = op.fill();
    op << hex << setfill('0');
  
    for (int i = 0; i < size; i++)
    {
        // Give space between two hex values
        if (i>0)
            op << ' ';
  
        // force output to use hex version of ascii code
        op << "0x" << setw(2) << static_cast(data[i]);
    }
  
    op.flags(old_flags);
    op.fill(old_fill);
}
  
void convert_to_struct(istream& ip, unsigned char* data,
                       int size)
{
    // Get the line we want to process
    string line;
    getline(ip, line);
  
    istringstream ip_convert(line);
    ip_convert >> hex;
  
    // Read in unsigned ints, as wrote out hex version
    // of ascii code
    unsigned int u = 0;
    int i = 0;
  
    while ((ip_convert >> u) && (i < size))
        if((0x00 <= u) && (0xff >= u))
            data[i++] = static_cast(u);
}
  
// Driver code
int main()
{
    Student_data student1 = {1, "Rohit"};
    ostringstream op;
  
    // Function call to convert 'struct' into 'hex string'
    convert_to_hex_string(op,
             reinterpret_cast(&student1),
             sizeof(Student_data));
  
    string output = op.str();
    cout << "After conversion from struct to hex string:\n"
         << output << endl;
  
    // Get te hex string
    istringstream ip(output);
    Student_data student2 = {0};
  
    // Function call to convert 'hex string' to 'struct'
    convert_to_struct(ip,
                reinterpret_cast(&student2),
                sizeof(Student_data));
  
    cout << "\nAfter Conversion form hex to struct: \n";
    cout << "Id \t: " << student2.student_id << endl;
    cout << "Name \t: "<< student2.name << endl;
  
    return 0;
}

输出:

After conversion from struct to hex string:
0x01 0x00 0x00 0x00 0x52 0x6f 0x68 0x69 0x74 0x00 0x00 0x00 0x00 0x00 
0x00 0x00 0x00 0x00 0x00 0x00

After Conversion form hex to struct: 
Id     : 1
Name     : Rohit
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”