C++中将结构体和字符串转换成可以用于类似jmeter传输的十六进制流

在一次项目,需要用到jmeter进行压力测试,但是需要将发送的字符串转成十六进制的字符流

下面是总结一个转换代码记录一下

#pragma pack(1)
using namespace std;

struct ACC_CMDHEAD
{
    unsigned short    m_wCmdType;        //请求类型
    unsigned short    m_wAttr;        //属性字段
    unsigned int    m_nLen;            //数据包的长度,不包括该数据头
    unsigned int    m_nExpandInfo;    //扩展信息,如果是请求数据,响应要原样返回
};


#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

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<int>(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<unsigned char>(u);
}

// Driver code
int main()
{
    ACC_CMDHEAD student1 = { 41125,512, 642, 0 };
    ostringstream op;

    // Function call to convert 'struct' into 'hex string'
    convert_to_hex_string(op,
        reinterpret_cast<const unsigned char*>(&student1),
        sizeof(ACC_CMDHEAD));

    string output = op.str();
    cout << "After conversion from struct to hex string:\n"
        << output << endl;

    // Get the hex string
    istringstream ip(output);
    ACC_CMDHEAD student2 = { 41125,512, 642, 0 };;

    // Function call to convert 'hex string' to 'struct'
    convert_to_struct(ip,
        reinterpret_cast<unsigned char*>(&student2),
        sizeof(ACC_CMDHEAD));

    cout << "\nAfter Conversion form hex to struct: \n";
    cout << "Id \t: " << student2.m_wCmdType << endl;
    cout << "Name \t: " << student2.m_nLen << endl;

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值