如何在Objective-C中使用struct.unpack并转换为值

0 投票
1 回答
1165 浏览
提问于 2025-04-16 15:55

这段代码是用Python写的

struct.unpack("< I",data.read(4))[0] # 将数据解包成整数。

这里的数据是从一个文件里读取的,然后用read方法来读取。

我想问的是,如何在Objective-C中使用read和struct.unpack。

我现在有的数据格式是NSFileHandle,可以一个字节一个字节地读取,所以读取数据不是问题。现在的问题是如何把我得到的NSData转换成(整数、短整数、浮点数、字符串)。

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

撰写回答