0
votes

I'm trying to convert this Javascript code:

self.userSerialEvent = function (join, value, tokens) {
        var type = join.charCodeAt(0);
        var rawJoin = parseInt(join.substr(1)) - 1;
        var rawValue = parseInt(value);
        self.SJValues[join] = value;

        var payload = "\x00\x00" + String.fromCharCode(value.length + 2) + "\x12" + String.fromCharCode(rawJoin) + value;
        self.sendMsg("\x05\x00" + String.fromCharCode(payload.length) + payload);
    };

to objective c code for an ipad app. However I cannot figure out how to properly form this If I do a char array I cannot have variable length (which will happen when the value is added to the array). And when I try to use NSMutableArray I cant insert bytes, plus my network send operation takes an NSData and I cannot convert a NSMutableArray to data. I have also tried NSString but when I do:

NSString * payload = [NSString stringWithFormat:@"0000%d12%d%@",value.length+2,rawJoin,[value dataUsingEncoding:NSASCIIStringEncoding]];

I get the < > around the data in the string. I have tried to create a character set and remove "<>" from the string but that only removed the end one (leaving the beginning < there)

My question is this: How can I form an array of bytes, that is of variable length and able to convert that array to NSData

1

1 Answers

5
votes

Sounds like you are looking for NSMutableData.

NSMutableData *payload = [[NSMutableData alloc] init];
[payload appendBytes:"\000\000" length:2];
uint8_t length = value.length + 2;
[payload appendBytes:&length length:1];
[payload appendBytes:"\022" length:1];
// etc.