備忘録

備忘録

C++で.NETのBinaryReaderのような事をする方法

Ⅰ. はじめに

タイトルの通り「C++で.NETのBinaryReaderのような事をする方法」です。

Ⅱ. サンプルプログラム

#include <iostream>
#include <string>

class BinaryReader
{
private:
  uint8_t *p;
  
public:
  BinaryReader(uint8_t *data)
  {
    this->p = data;
  }

  template<typename T>
  T read()
  {
    auto p = reinterpret_cast<T*>(this->p);
    this->p += sizeof(T);
    return *p;
  }

  template<typename T>
  std::string readString()
  {
    auto length = *reinterpret_cast<T*>(this->p);
    this->p += sizeof(T);

    std::string str(reinterpret_cast<char*>(this->p), length);
    this->p += length;

    return str;
  }
};

int main() {
  uint8_t data[] = {
    0x01, 0x00, // ID(2バイト)
    0x06, 0x00, 0x00, 0x00, // Nameの長さ(4バイト)
    0x74, 0x61, 0x6e, 0x61, 0x6b, 0x61, // Name(tanaka)
    0x14 // Age(1バイト)
  };

  BinaryReader reader(data);

  auto id = reader.read<uint16_t>();
  auto name = reader.readString<uint32_t>();
  auto age = reader.read<uint8_t>();

  std::printf("Id: %d\n", id);
  std::printf("Name: %s\n", name.c_str());
  std::printf("Age: %d\n", age);

  return 0;
}

実行結果

Id: 1
Name: tanaka
Age: 20