1

I got a problem implementing a PHP programm in C++. It is about the PHP/Perl function unpack. I don't know how to do the follwing in C++ (no problem in reading a file... but how do i unpack("C*") the read contents).

<?php
$file = fopen("bitmaskt.dat", "rb");
//create the data stream
$matrix_x           = unpack("C*", fread($file, 286));
$matrix_y           = unpack("C*", fread($file, 286));
$mask_data          = unpack("C*", fread($file, 286));
$reed_ecc_codewords = ord(fread($file, 1));
$reed_blockorder    = unpack("C*", fread($file, 128));
fclose($file);
?>

Currently, I'm very hopeless solving this problem on my own - I'm searching for days, all I found are questions... Is there any free unpack() c++ implementation out there? :-(

4

2 に答える 2

2

Perl のドキュメントにpackpackは、および で使用されるテンプレートが含まれていunpackます。

bitmaskt.datで生成したとしましょう

#! /usr/bin/perl

use warnings;
use strict;

open my $fh, ">", "bitmaskt.dat" or die "$0: open: $!";

my @data = (42) x 286;

print $fh pack("C*" => @data);
print $fh pack("C*" => @data);
print $fh pack("C*" => @data);
print $fh pack("C"  => 7);
print $fh pack("C*" => (1) x 128);

close $fh or warn "$0: close";

あなたはそれを読むかもしれません

#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>

typedef unsigned char datum_t;
typedef std::vector<datum_t> buf_t;

std::istream &read_data(std::istream &in, buf_t &buf, size_t n)
{
  std::istreambuf_iterator<char> it(in.rdbuf()), eos;
  while (it != eos && n-- != 0)
    buf.push_back(static_cast<datum_t>(*it++));

  return in;
}

例えば:

int main()
{
  std::ifstream bm("bitmaskt.dat", std::ifstream::binary | std::ifstream::in);

  struct {
    buf_t buf;
    size_t len;
    std::string name;
  } sections[] = {
    { buf_t(), 286, "matrix_x" },
    { buf_t(), 286, "matrix_y" },
    { buf_t(), 286, "mask_data" },
    { buf_t(),   1, "reed_ecc_codewords" },
    { buf_t(), 128, "reed_blockorder" },
  };
  const int n = sizeof(sections) / sizeof(sections[0]);

  for (int i = 0; n - i > 0; i++) {
    if (!read_data(bm, sections[i].buf, sections[i].len)) {
      std::cerr << "Read " << sections[i].name << " failed" << std::endl;
      return 1;
    }
  }

  const int codeword = 3;
  std::cout << (unsigned int) sections[codeword].buf[0] << '\n';

  return 0;
}

出力:

7
于 2010-01-29T18:05:47.647 に答える
1

C++ の unpack の一般的な実装については知りませんが、とにかく必要なものではないようです。

matrix_x がどこかで定義されunsigned char matrix_x[286]ていて、開いている入力ストリームがあるinFile 場合、あなたがする必要があるのはinFile.get(matrix_x, 286). これは、入力から 286 バイトを読み取り、 が指す配列に配置しmatrix_xます。

于 2010-01-29T17:16:44.480 に答える