0

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?

Patrick
  • 7,903
  • 11
  • 52
  • 87

2 Answers2

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

0

One variation

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

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

// send the data
JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • This assumes `myStringIWantToSend` has one character only. `nullLeader` must, hmm, lead every character in the string. –  May 06 '11 at 09:35
  • That seems quite bizarre. Are you sure it is not simple that the character encoding is some 32 bit variant of Unicode? – JeremyP May 06 '11 at 10:42
  • I found it odd, too. But my quick search on Quartz Composer protocols didn’t return anything relevant. –  May 06 '11 at 10:45
  • I got the network part from this site: http://arrifana.org/blog/2007/11/leopards-quartz-composer-and-network-events/. I think it's pretty weird, but I'm trying since two days already and I'm happy to have a solution now. – Patrick May 06 '11 at 11:13