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 的文档pack涵盖了用于pack和的模板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 回答