1

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 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

5 Comments

awesome thank you, i should have figured nsmutabledata. thanks again. (5mins till i can accept)
i have been doing 0x01 for hex bytes, but for this i will use /001 ?
@owengerig 0x01 is the integer literal with that hex value. If you put it in a string then it'll just be the character stream of a 0 followed by an x followed by a 0, et seq. C strings (as used here) allow byte values to be inserted directly into the character sequence with either \ooo where each o is an octal digit or \xhh where h is a hexadecimal digit (which appears to be what you're doing in the Java original?)
I wasn't sure if "\x01" was valid in current Objective-C (it was not part of the language when I learned it), but it is indeed valid now. Octal escapes have always been valid.
Hex A = octal 12 = decimal 10.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.