Additional characters in NSString for network transfer

风格不统一 提交于 2019-12-25 08:47:45

问题


Due to some protocol specifications for Quartz Composer, the string "\0\0\0" has to precede every character sent via UDP. The current value has this format: "1.23456". For the transfer the last three decimal places are not required, but the addition before every number, so it should look like this: "\0\0\01\0\0\0.\0\0\02\0\0\03". What's "the Objective-C way" to solve this?


回答1:


If I understood you correctly, you want to send a sequence of characters (type char). In that case,

NSString *originalString = @"1.23456";

// It's not clear if you must remove the last three digits
// so I'm assuming that the string always has the last three
// characters removed

NSUInteger stringLength = [originalString length];
if (stringLength > 3)
    originalString = [originalString substringToIndex:stringLength - 3];

// I'm assuming ASCII strings so that one character maps to only one char
const char *originalCString = [originalString cStringUsingEncoding:NSASCIIStringEncoding];

if (! originalCString) {
    NSLog(@"Not an ASCII string");
    exit(1);
}

NSMutableData *dataToSend = [NSMutableData data];
char zeroPadding[] = { 0, 0, 0 };
NSUInteger i = 0;
char character;

while ((character = originalCString[i++])) {
    [dataToSend appendBytes:zeroPadding length:sizeof zeroPadding];
    [dataToSend appendBytes:&character length:1];
}

If you run

NSLog(@"%@", dataToSend);

the output should be

<00000031 0000002e 00000032 00000033>

where

00000031

means

00 00 00 31

and 31 is the ASCII code of ‘1’ (2e = ‘.’, 32 = ‘2’, 33 = ‘3’).

If you need to know the size (in bytes) of dataToSend, use [dataToSend length]. If you want to access the bytes themselves, use [dataToSend bytes].




回答2:


One variation

NSMutableData* dataToSend;
char nullLeader[] = { 0, 0, 0 };

dataToSend = [NSMutableData dataWithBytes: nullLeader length: sizeof nullLeader];
[dataToSend appendData: [myStringIWantToSend dataUsingEncoding: NSUTF8StringEncoding]];

// send the data


来源:https://stackoverflow.com/questions/5909254/additional-characters-in-nsstring-for-network-transfer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!