0

Python でのコード

struct.unpack("< I",data.read(4))[0] # int に展開します。

データはファイルから読み取られ、次に read が使用されます。私の質問は、Objective-c で struct.unpack を使用、読み取り、およびアンパックする方法です。

バイトごとに読み取ることができる NSFileHandle 形式のデータがあるので、読み取りは今のところ問題ありません。問題は、取得した NSData を (int、short、float、string) に変換することです。

4

1 に答える 1

1

Objective-Cについてはわかりませんが、プレーンCでは次を使用できますfread()

#include <inttypes.h> /* uint32_t and PRIu32 macros */
#include <stdbool.h> /* bool type */
#include <stdio.h>

/* 
   gcc *.c && 
  python -c'import struct, sys; sys.stdout.write(struct.pack("<I", 123))' |
  ./a.out 
*/

static bool is_little_endian(void) {
  /* Find endianness of the system. */
  const int n = 1;
  return (*(char*)&n) == 1; /* 01 00 00 00 for little-endian */
}

static uint32_t reverse_byteorder(uint32_t n) {
  uint32_t i;
  char *c = (char*) &n;
  char *p = (char*) &i;
  p[0] = c[3];
  p[1] = c[2];
  p[2] = c[1];
  p[3] = c[0];
  return i;
}

int main() {
  uint32_t n; /* '<' format assumes 4-byte integer */

  if (fread(&n, sizeof(n), 1, stdin) != 1) {
    fprintf(stderr, "error while reading unsigned from stdin");
    return 1;
  }

  if (! is_little_endian()) 
    /* convert from big-endian to little-endian ('<' format) */
    n = reverse_byteorder(n);

  printf("%" PRIu32 " 0x%08x\n", n, n);
  return 0;
}

出力

123 0x0000007b
于 2011-04-17T17:52:19.840 に答える