NSString中用于网络传输的其他字符 [英] Additional characters in NSString for network transfer

查看:47
本文介绍了NSString中用于网络传输的其他字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Quartz Composer的某些协议规范,字符串"\ 0 \ 0 \ 0"必须位于通过UDP发送的每个字符之前.当前值的格式为:"1.23456".对于传输而言,不需要最后三个小数位,而是在每个数字前加一个小数,因此它应如下所示:"\ 0 \ 0 \ 01 \ 0 \ 0 \ 0. \ 0 \ 0 \ 02 \ 0 \ 0\ 03.解决这个问题的"Objective-C方法"是什么?

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?

推荐答案

如果我对您的理解正确,则希望发送一个字符序列(类型为 char ).在这种情况下,

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];
}

如果您运行

NSLog(@"%@", dataToSend);

输出应为

<00000031 0000002e 00000032 00000033>

其中

00000031

表示

00 00 00 31

并且31是ASCII码"1"(2e =.",32 ="2",33 ="3").

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

如果您需要了解 dataToSend 的大小(以字节为单位),请使用 [dataToSend length] .如果要访问字节本身,请使用 [dataToSend bytes] .

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].

这篇关于NSString中用于网络传输的其他字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆