实现一个简单的 C++ BinaryReader类

实现一个简单的 C++ BinaryReader类

在C++网络编程中通常需要自己拼包来发送数据,以下是一个简单的BinaryReader类

BinaryWriter 看这里!

1. 完整代码

// BinaryReader.h
//
// Created by xxx on 2023-12-24.
//

#ifndef BINARYREADER_H
#define BINARYREADER_H
#include <iostream>
#include <vector>
#include <cstdint>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>

class BinaryReader
{
public:
    explicit BinaryReader(const std::vector<uint8_t> &buffer, bool flipBytes = false)
            : _buffer(buffer), _flipBytes(flipBytes), _offset(0) {}

    // 设置字节顺序
    void setByteOrder(bool flipBytes)
    {
        _flipBytes = flipBytes;
    }

    // 读取数据到目标变量
    template <typename T>
    BinaryReader &readData(T &value)
    {
        if (_offset + sizeof(T) <= _buffer.size())
        {
            std::memcpy(&value, &_buffer[_offset], sizeof(T));
            if (_flipBytes)
            {
                flipByteOrder(value);
            }
            _offset += sizeof(T);
        }
        return *this;
    }

    // 读取字符串
    BinaryReader &readData(std::string &value)
    {
        value.clear();
        while (_offset < _buffer.size() && _buffer[_offset] != 0)
        {
            value.push_back(static_cast<char>(_buffer[_offset]));
            ++_offset;
        }

        ++_offset;
        return *this;
    }

    // 读取指定长度的字符串
    BinaryReader &readData(std::string &value, std::size_t length)
    {
        value.clear();
        while (_offset < _buffer.size() && length > 0)
        {
            value.push_back(static_cast<char>(_buffer[_offset]));
            ++_offset;
            --length;
        }
        return *this;
    }

    // 获取当前偏移量
    [[nodiscard]] std::size_t getOffset() const
    {
        return _offset;
    }

private:
    // 翻转字节顺序
    template <typename T>
    void flipByteOrder(T &value)
    {
        char *bytes = reinterpret_cast<char *>(&value);
        for (std::size_t i = 0; i < sizeof(T) / 2; ++i)
        {
            std::swap(bytes[i], bytes[sizeof(T) - i - 1]);
        }
    }

    const std::vector<uint8_t> &_buffer;
    bool _flipBytes;
    std::size_t _offset;
};

#endif //BINARYREADER_H

2. 构造函数

explicit BinaryReader(const std::vector<uint8_t> &buffer, bool flipBytes = false);

构造函数接收一个字节缓冲区作为参数,并可选地指定是否在读取时翻转字节顺序。

3. setByteOrder

void setByteOrder(bool flipBytes);

这个方法用于设置字节顺序,可以在读取过程中动态切换字节顺序。
下面将讲些为何需要设置字节顺序:

在不同的计算机体系结构之间传递二进制数据,计算机体系结构可以采用不同的字节顺序,其中两种常见的顺序是大端序(Big-Endian)和小端序(Little-Endian)。

大端序(Big-Endian):在内存中,高位字节存储在低地址,低位字节存储在高地址。

小端序(Little-Endian):在内存中,低位字节存储在低地址,高位字节存储在高地址。

如果一个程序在一个大端序的计算机上生成了二进制数据,并且这个数据需要传递给一个小端序的计算机进行处理,或者反之,那么就需要考虑字节顺序的问题。

动态切换字节顺序的情况通常发生在跨越不同计算机体系结构的网络通信中,或者在读取/写入文件时。例如,一个程序可能需要将数据写入文件并在之后的执行中从文件中读取,而这两个操作发生在不同的计算机体系结构上。

在这种情况下,通过动态切换字节顺序,可以确保在读取数据时按照目标系统的字节顺序进行解释,保持数据的一致性和正确性。

4. readData

template <typename T>
BinaryReader &readData(T &value);

该模板方法用于读取各种基本类型的数据,包括整数、浮点数等。根据字节顺序设置,它会自动翻转字节顺序。

5. readData(std::string &value)

BinaryReader &readData(std::string &value);

用于读取以空字符结尾的字符串,将字符串数据附加到传入的value中。

6. readData(std::string &value, std::size_t length)

BinaryReader &readData(std::string &value, std::size_t length);

读取指定长度的字符串,将字符串数据附加到传入的value中。

7. getOffset

[[nodiscard]] std::size_t getOffset() const;

返回当前读取位置的偏移量。

示例程序

#include "BinaryReader.h"

int main() {
    std::vector<uint8_t> data = {0x01, 0x02, 0x03, 0x04};

    BinaryReader reader(data);

    int intValue;
    reader.readData(intValue);

    std::cout << "Read Integer: " << intValue << std::endl;

    std::string stringValue;
    reader.readData(stringValue);

    std::cout << "Read String: " << stringValue << std::endl;

    return 0;
}

有发现错误或者优化请指正,谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值