[英]how to encode a UInt32 scalar type into a NSData object
我目前正在創建此NSData對象。 我想放一些NSString和UInt32類型的不同對象。 我知道如何將NSString放入我的NSData對象中,但是我不知道如何使用UInt32標量類型來做到這一點。
這就是我使用NSString的方法
- (void) constructRequest
{
NSString *mystring = [[NSString alloc] initWithString:[self addMethodName]];
UInt32 protocolInt = [self addProtocolVersion];
NSData* data=[mystring dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:@"/Users/imac/Desktop/_dataDump.dat" atomically:YES];
}
因此,我已經弄清楚了,不僅要更新我的問題,我還要輸入答案,以便其他人看到他們正在做類似的事情時,已經回答了這個問題。
代碼如下
- (void) constructRequest
{
//NSString *mystring = [[NSString alloc] initWithString:[self addMethodName]];
UInt32 protocolInt = [self addProt];
NSData * data = [[NSData alloc] initWithBytes:&protocolInt length:sizeof(protocolInt)];
//NSData* data=[mystring dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:@"/Users/imac/Desktop/_dataDump.dat" atomically:YES];
}
是否需要使用NSData? 您可以使用NSString或NSNumber(都可以保存在屬性列表中)。
如果重要的話,您的方案實際上不會區分4字節字符串和UInt32。
您可以使用htonl()
, htons()
, ntohl()
和ntohs()
使其具有字節序安全性。
htonl()--"Host to Network Long int" 32Bytes
ntohl()--"Network to Host Long int" 32Bytes
htons()--"Host to Network Short int" 16Bytes
ntohs()--"Network to Host Short int" 16Bytes
例:
- (void)testExample {
UInt32 length = 0x1a2b3c4d;
NSLog(@"%x", length);
length = htonl(length);
NSLog(@"%x", length);
NSMutableData *data = [[NSMutableData alloc] init];
[data appendBytes:&length length:4];
NSLog(@"%@", data);
}
打印:
2015-10-29 15:46:49.224 UPHTTP-iOS[3896:101301] 1a2b3c4d
2015-10-29 15:46:49.224 UPHTTP-iOS[3896:101301] 4d3c2b1a
2015-10-29 15:46:49.224 UPHTTP-iOS[3896:101301] <1a2b3c4d>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.