将NSdata转换为字节&然后将前n个字节转换为int [英] Converting NSdata to bytes & then converting the first n bytes to int
问题描述
我有一个NSData对象,首先我要将NSData对象转换为字节,然后读取此NSData对象中的前四个字节&然后将前四个字节转换为它们的等效整数值。
关于如何解决这个问题的任何想法?
I've an NSData object, First I want to convert NSData object to bytes, then read the first four bytes in this NSData object & then convert the first four bytes to their equivalent integer values. Any ideas on how to go about this?
如何将所有四个字节转换为单个正整数值?
How about converting all the four bytes to a single positive integer value?
推荐答案
从原始数据中获取int是不明确的:数据来自何处?你想要什么尺寸的int?你想让他们签名或签名吗?您期望什么字节排序?
Getting an int out of raw data is ambiguous: where does the data come from? What size do you want your int? Do you want them signed or unsigned? What byte ordering do you expect?
所以这里有一个场景:您获得的数据来自外部进程编码的流,该进程以32位有符号整数形式提供大量内容 - 印度订单。以下是你可以这样做的方法:
So here is one scenario: the data you get is from a stream encoded by an external process that feeds 32-bit signed ints in big-endian order. Here's how you could do it:
NSData *dataFromStream = functionThatReturnsNSData();
SInt32 *signedInt32pointer = [dataFromStream bytes];
SInt32 unSwappedInt32 = *signedInt32pointer;
SInt32 reorderedInt32 = CFSwapInt32BigToHost(unSwappedInt32);
RTFM核心基础内存管理编程指南的字节排序和字节交换部分。
RTFM the Byte ordering and byte swapping sections of the Memory Management Programming Guide for Core Foundation.
这篇关于将NSdata转换为字节&然后将前n个字节转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!