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 回答