2024-07-05 09:09:18 发布
网友
Python代码
struct.unpack("< I",data.read(4))[0] # Unpack to int.
从文件中读取数据,然后使用read, 我的问题是我们如何使用、阅读和解包结构在目标c中
我有NSFileHandle格式的数据,可以逐字节读取,所以现在读取不是问题。问题是把我得到的NSData转换成(int,short,float,string)。在
我不知道Objective-C,但在普通C中,您可以使用^{}:
#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; }
我不知道Objective-C,但在普通C中,您可以使用^{} :
输出
^{pr2}$相关问题 更多 >
编程相关推荐